Taking exit as user input

May 6, 2015 at 7:43pm
I'm currently writing a gradebook application in which the user would enter grades and I would store them in an array. When the user enters "exit", the program exits and prints out a histogram of the entries the user entered. However, when I enter "exit" into my program, the console tells me abort() has been called. Is there a way around this?
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
26
27
void printArray(string string_array[], int size){
	for (int i = 0; i < size ; i++){
		cout << i << string_array[i] << endl;
	}

}
  void Problem1(){
	string string_array[10];
	string user_input;
	int array_index;

	while (user_input != "exit"){
		cout << "Please enter the student's grade between 0 - 100: ";
		cin >> user_input;
		if (user_input == "exit"){
			printArray(string_array, 10);
		}
		else if (stoi(user_input) < 0 || stoi(user_input) > 100){
			cout << "Error, please re-enter the student's grade between 0 - 100: ";
			cin >> user_input;
		}
		array_index = stoi(user_input) / 10;
		string_array[array_index] = "#";
		//cout << string_array[array_index] << endl;
			
	}
}


The # sign is for every grade the user entered for that index.
May 6, 2015 at 8:18pm
Pretty sure the problem is line 22, if you enter "exit", line 22 will try run stoi("exit"), which would either cause some exception or undefined behavior.
Change line 15-17 to be
1
2
3
4
		if (user_input == "exit"){
			printArray(string_array, 10);
                        break;
		}

would probably be the easiest way to remedy this, but just note that excessive use for things like "break;" or "continue;" can make code hard to navigate when debugging.
Last edited on May 6, 2015 at 8:20pm
Topic archived. No new replies allowed.