Why the while loop exit in c++ when I enter a string
operator>>
performs error handling internally. If it fails to extract an integer, the stream enters a failure state, and the loop is checking the stream's state, so it exits when the stream fails.
in c# if I don't use tryparse it will give an exception.
Yes, because that is the way int.parse()
is defined to work.
You can get similar behavior in C++ by enabling exceptions in the stream . That way, if an extraction failure occurs, a std::ios_base::failure
exception is thrown.
Does the c++ explicitly do something like tryparse in the backend ?
In a way, yes.
I am reading the book c++ primes and code a simple program that continuously takes integer as input until a string is entered. I wrote the same code in c# but it leads me to an error.
Your C++ and C# codes are not equivalent.
Your C# code reads an entire line as-is, discarding the line break, and then tries to convert the entire line as-is to an int.
Your C++ code discards leading whitespace - including line breaks - until it encounters a non-whitespace character, then it tries to read an int value, and whatever follows after it - including a line break - remains in the stream for subsequent reads.
So I have to use tryparse method in C#.
If you don't want a failed conversion to throw an exception, then yes.