- 2
How can I make a program that takes input from the user and stores the values in an array until the user types 'stop'?
4 ответов
+ 3
Here is how you can store integers instead (adapted from Mohammed's code):
http://code.sololearn.com/chmx6AO37t0r
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int x=0, lim=10; // for specifying the limit for no. of inputs
int value[lim];
string str = "";
while ((x < lim) && (str != "stop")) {
cout << "Enter the value: ";
cin >> str;
cout << str << endl;
if (str != "stop") {
value[x] = atoi(str.c_str());
x++;
}
}
for (int i = 0; i < x; i++) // for printing the values
cout << value[i] << " ";
return 0;
}
+ 1
#include <iostream>
using namespace std;
int main()
{
int x=0, lim=10; // for specifying the limit for no. of inputs
string value[lim], str;
while(str != "stop")
{
cout << endl << "Enter the value: ";
cin >> str;
value[x] = str;
x++;
}
for(int i=0; i<(x-1); i++) // for printing the values
cout << endl << value[i];
return 0;
}
- 1
what if i wanted to input numbers rather than string?
should I use an int array instead of the string str ?
- 3
I think this is not possible unless you use special means. Because you can't type cast an int into a string or vice versa. What you might do is function overloading. Making same functions but one with int and one with string datatype parameter. Then you can use int typed for the input and string typed to stop the loop. But i am not quite sure that it will work perfectly as i have not tried it.