In short, I don't see what I'm doing wrong with my for loop. It should ask for input twice on 2 separate lines but it only asks for input ONCE then outputs the next part. Strangely enough, it works when I use cin & only input 1 word per line but not when I'm using getline() and multiple words per line. I looked up the syntax for getline() and it looks like I'm doing it correctly. So I don't know what the issue is.
Current Input:
1 2
2 1
this is a test
NOTE: it does not give me the chance to put in the second line
/*
N = # of contestants in the contest. N must be >= 1.
P = total # of difficult problems solved. P must be <= 1000.
*/
#include <iostream>
#include <string>
int main() {
int N; // number of contestants in contest
int P; // total # of difficult problems solved
std::string ignoreString;
//std::cout << "Please enter the number of contestants in contest THEN the total # of difficult problems solved: \n";
std::cin >> N >> P;
for (int i = 0; i < N; i++) {
//std::cin >> ignoreString; // works as intended IF only 1 word per line. I need it to work no matter if there are 1 or 2+
std::getline(std::cin, ignoreString);
}
if ((N > 0) && (P <= 1000))
std::cout << P; // outputs # of difficult problems solved
}
Help would be greatly appreciated. I've spent over an hour on this and still don't know what I'm doing wrong...
@dutch Thanks, I read your solution. However, it still is having problems.
When I added the cin.ignore(...) line, the input could be:
1 2 3 4
2 1
ss ss
ss ss
ss ss
And the output be: 1
But the input should only have 2 lines (after the "2 1" line).
- - - - - - -
Also, you said to do this:
1 2
string line;
getline(cin, line); // read a complete line, which includes extracting the newline
Which is exactly what I did, just using a different variable name and yours was using "using namespace std;".
- - - - - - -
Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <string>
int main() {
int N; // number of contestants in contest
int P; // total # of difficult problems solved
std::string ignoreString;
//std::cout << "Please enter the number of contestants in contest THEN the total # of difficult problems solved: \n";
std::cin >> N >> P;
for (int i = 0; i < N; i++) {
//std::cin >> ignoreString; // works as intended IF only 1 word per line. I need it to work no matter if there are 1 or 2+
std::getline(std::cin, ignoreString);
std::cin.ignore(10000, '\n');
}
if ((N > 0) && (P <= 1000))
std::cout << P; // outputs # of difficult problems solved
}
You put the ignore in the wrong place. It doesn't make sense to put it after the getline since the getline extracts the newline itself. Instead you need to put it after the cin >> N >> P, which does not extract the newline. The ignore will extract the newline so that the getline can read the next line.