A
algorithm
Hi,
I've a simplified program snippet in which getline behaves in a way, which
at least I find odd:
// File: getline_example.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
int one;
if (cin >> one)
{
cout << "one: " << one << endl;
string two;
if (getline(cin,two))
{
cout << "two: " << two << endl;
string three;
if (getline(cin,three))
{
cout << "three: " << three << endl;
}
else
{
cout << "third error." << endl;
}
}
else
{
cout << "second error." << endl;
}
}
else
{
cout << "first error." << endl;
}
}
Using g++ 3.4.2 with the following input results in the following:
$ g++ getline_example.cpp
$ ./a.exe
42
one: 42
two:
I.e. I start program and it is waiting for input.
I enter 42 and hits return.
As expected the program outputs what I just inputed.
However, the program outputs "two:" as well!?!?!?
This is very odd to me since I have only entered one data input (42). I
was expecting that the program was awaiting a second set of indata but no
- it just goes on and instead it is waiting for a third set of data!?!?
I have no idea what or why the statement getline(cin,two) did! But I do
know that it did not wait for my second set of indata :-(
Is it me or is it g++ who gets this wrong. (I do not think that g++ should
get this trivial case wrong, so...)
Thanks in advance!
PS. Do not advise me to add advanced error-checking and resetting a state
flag or the like because that should really not be nescessarry. (State is
checked in the if statements.)
I've a simplified program snippet in which getline behaves in a way, which
at least I find odd:
// File: getline_example.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
int one;
if (cin >> one)
{
cout << "one: " << one << endl;
string two;
if (getline(cin,two))
{
cout << "two: " << two << endl;
string three;
if (getline(cin,three))
{
cout << "three: " << three << endl;
}
else
{
cout << "third error." << endl;
}
}
else
{
cout << "second error." << endl;
}
}
else
{
cout << "first error." << endl;
}
}
Using g++ 3.4.2 with the following input results in the following:
$ g++ getline_example.cpp
$ ./a.exe
42
one: 42
two:
I.e. I start program and it is waiting for input.
I enter 42 and hits return.
As expected the program outputs what I just inputed.
However, the program outputs "two:" as well!?!?!?
This is very odd to me since I have only entered one data input (42). I
was expecting that the program was awaiting a second set of indata but no
- it just goes on and instead it is waiting for a third set of data!?!?
I have no idea what or why the statement getline(cin,two) did! But I do
know that it did not wait for my second set of indata :-(
Is it me or is it g++ who gets this wrong. (I do not think that g++ should
get this trivial case wrong, so...)
Thanks in advance!
PS. Do not advise me to add advanced error-checking and resetting a state
flag or the like because that should really not be nescessarry. (State is
checked in the if statements.)