Reputation: 452
I am writing some code to read from the terminal with cpp but for some reason it crashed after running out of numbers. From what I have read online I should be able to check if std::cin
was successful by using std::cin.fail()
but it crashes before.
The code I am running is
#include <iostream>
int main()
{
int x{};
while (true)
{
std::cin >> x;
if (!std::cin)
{
std::cout << "breaking" << '\n';
break;
}
std::cout << x << '\n';
}
return 0;
}
with the input:
test@test:~/learn_cpp/ex05$ ./test
1 2
1
2
^C
I end up having to ctrl+c out of the program. Version info:
gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Upvotes: 1
Views: 403
Reputation: 10022
Nothing in your input causes cin
to set the fail bit. Hence, the while (true)
will just keep going. You can enter a letter, or something which is otherwise not an int
, which will set the fail bit, and cause the loop to break.
Note that a new line will be ignored for this purpose.
If you know that all your input will be on a single line, then you can use std::getline
to read in the entire line, and then std::stringstream
to read the integers from that line.
#include <iostream>
#include <sstream>
#include <string>
int main() {
int x{};
std::string buff;
std::getline( std::cin, buff );
std::stringstream ss( buff );
while ( ss >> x ) {
std::cout << x << '\n';
}
return 0;
}
Upvotes: 3