[issue] code not reading for loop properly

An assignment from school that I'm having a little bit of issues with. The output after the first rotation of information input doesn't allow for the input of the students name. Not sure whats causing this skip... could use another pair of eyes

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
28
#include <string>
#include <iostream>

using namespace std;

const int array_size = 10;

int main()
{
    string names[array_size];
    int scores[array_size];
    int smol;
    double average, average2;

    for (int i = 0; i < array_size; i++)
    {
        cout << "Enter student " << i + 1 << "\n > ";
        getline(cin, names[i]);        
        cout << "Enter student " << i + 1 << "'s score\n > ";
        cin >> scores[i];
        while (scores[i] < 0 || scores[i] > 100)
        {
            cout << "Incorect Value! Re-enter.\n > ";
            cin >> scores[i];
        }
        cout << names[i] << endl;
    }
}
Last edited on
You are mixing >>, which leaves the end-of-line character in the input stream, with getline(), which doesn't. You can use (amongst other possible choices):
cin.ignore(1000,'\n');
after your stream extraction calls, to remove '\n' before it gets picked up by the next getline().

You are also trying to run before you can walk - the input validation (lines 21-25) is something that you can add after getting the rest to work. Develop code slowly. Ditto the set of currently unused (and never likely to be used) variables in lines 12 and 13.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <string>
#include <iostream>

constexpr size_t array_size {10};

int main() {
	std::string names[array_size];
	int scores[array_size] {};

	for (size_t i = 0; i < array_size; ++i) {
		std::cout << "Enter student " << i + 1 << "'s name: ";
		std::getline(std::cin, names[i]);

		std::cout << "Enter student " << i + 1 << "'s score: ";

		do {
			std::cin >> scores[i];
			std::cin.clear();
		} while (std::cin.ignore(1000, '\n') && (scores[i] <= 0 || scores[i] > 100) && std::cout << "Incorrect Value! Re-enter: ");
	}

	for (size_t i = 0; i < array_size; ++i)
		std::cout << names[i] << "\t\t" << scores[i] << '\n';
}

Topic archived. No new replies allowed.