- 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'?

12th Sep 2016, 10:24 AM
Aryan Pandey
Aryan Pandey - avatar
4 Answers
+ 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; }
12th Sep 2016, 5:13 PM
Zen
Zen - avatar
+ 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; }
12th Sep 2016, 11:32 AM
Mohammed Maaz
Mohammed Maaz - avatar
- 1
what if i wanted to input numbers rather than string? should I use an int array instead of the string str ?
12th Sep 2016, 11:38 AM
Aryan Pandey
Aryan Pandey - avatar
- 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.
12th Sep 2016, 12:00 PM
Mohammed Maaz
Mohammed Maaz - avatar