acorn
My knowledge of the
iostream is rather limited.
Of cause, with synchronization we get rid of unread characters and ensure that cin.ignore() won't unexpectedly catch the '\n' escape from unread symbols.
However... It might be that we, in fact, need those symbols.
I'm confused... So, better to be careful with sync() call.
why i didnt need to add limits to this and have it still work |
I've thought out a situation when we really have to include limits.
Consider the next code:
1 2 3 4 5 6 7 8
|
std::string firstNameStr, secondNameStr;
std::cout << "What is your first name?" << std::endl;
std::cin >> firstNameStr;
std::cout << "What is your second name?" << std::endl;
std::cin >> secondNameStr;
std::cout << firstNameStr << std::endl;
std::cout << secondNameStr << std::endl;
|
And now imagine Leeloo is trying to insert her name :-)
Leeloo Minai Lekarariba-Laminai-Tchai Ekbat De Sebat
The out will be somewhat like:
And the program wouldn't even give her a chance to insert the second name.
With the aid of cin.ignore() trick we can avoid such a pity.
1 2 3 4 5 6 7 8 9
|
std::string firstNameStr, secondNameStr;
std::cout << "What is your first name?" << std::endl;
std::cin >> firstNameStr;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n')
std::cout << "What is your second name?" << std::endl;
std::cin >>secondNameStr;
std::cout << firstNameStr << std::endl;
std::cout << secondNameStr << std::endl;
|
And now everything is working as we may expect!
And the output will be:
The first name is still corrupted, nevertheless she is able to insert her second name :-)