Getline keeps on getting newline character. How can I avoid this?
you just need to accept the fact that getline will give you '\n' at the end. One solution is remove '\n' after getting it. Another solution is do not write the additional 'endl'. for example, for your problem, you can use this code
int N;
cin >> N;
string line;
getline(cin, line); // skip the first new line after N.
for (int i = 0; i < N; i++) {
string line;
getline(cin, line);
string first4 = line.substr(0, 4);
// convert to upper case.
std::transform(first4.begin(), first4.end(), first4.begin(), std::ptr_fun<int, int>(std::toupper)); // see http://en.cppreference.com/w/cpp/algorithm/transform
if (first4 == "HI A") {
cout << line; // do not include "<< endl"
}
}
Your cin >>N
stops at the first non-numeric character, which is the newline. This you have a getline
to read past it, that's good.
Each additional getline
after that reads the entire line, including the newline at the end. By putting in a second getline
you're skipping half your input.
ignore() function does the trick. By default, it discards all the input suquences till new line character.
Other dilimiters and char limit can be specified as well.
http://www.cplusplus.com/reference/istream/istream/ignore/
In your case it goes like this.
cin >> N;
cin.ignore();
So, your real problem isn't that getline
eats newlines, but that your second getline(cin, ne)
is eating a line...
And that is because you mistakenly think that you need two getline
operations to read one line - or something like that. Mixing "linebased" and "itembased" input does have confusing ways to deal with newlines, so you do need something to "skip" the newline left behind frin cin >> N;
, but once you have got rid of that, you only need ONE getline
to read up and including the newline at the end of a line.