String into a int loop

So Im trying to have the user be able to type the word done (and have the program stop), into a loop that finds the average of up to 15. I cant figure out how, am I even on the right track?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int total = 0;
	const int sizeofarray = 15;
	int numbers[sizeofarray];
	string end = "";

	cout << "Please enter up to 15 numbers" << endl;
	cout << "You can stop at anytime by typing 'done'" << endl;
	cout << "Please enter a number: ";

	for (int i = 0; i < sizeofarray; i++) {
		cout << "Please enter another number, or say done: ";
		cin >> numbers[i];
		total += numbers[i];

		while (end != "done") {
			cin >> end;

			if (end != "done") {
				numbers[i] = atoi(end.c_str());
			
			
			}
		}
		cout << "The average is " << (float)total / sizeofarray << endl;
	}
Last edited on
Please edit your post and make sure your code is [code]between code tags[/code] so that it has line numbers and syntax highlighting, as well as proper indentation.

You want something like this:
1
2
3
4
5
6
7
8
9
10
std::vector<int> numbers;
std::string line;
while(std::getline(std::cin, line) && line != "end")
{
    int v;
    if(std::istringstream{line} >> v)
    {
        numbers.push_back(v);
    }
}
http://www.LB-Stuff.com/user-input
http://www.cplusplus.com/reference/vector/vector/
http://en.cppreference.com/w/cpp/container/vector
http://www.cplusplus.com/reference/sstream/istringstream/
http://en.cppreference.com/w/cpp/io/basic_istringstream
OK, I think Ive fixed my post. But i do not understand what you did there, or how to implement it.
1
2
3
4
for (int i = 0; i < sizeofarray; i++) {
            cout << "Please enter another number, or say done: ";
            cin >> numbers[i];
....


What is happening if user input "done" here ? numbers[i] = "done" ?
just an infinite loop of "Please enter another number, or say done:
b29hockey wrote:
i do not understand what you did there, or how to implement it.
Read the links I provided ;)
Topic archived. No new replies allowed.