[英]why cursor not go to next line? When getline() take "\n" as an input
I was learning from https:\/\/www.learncpp.com\/cpp-tutorial\/an-introduction-to-stdstring\/<\/a> and a question arises from the below code我正在从
https:\/\/www.learncpp.com\/cpp-tutorial\/an-introduction-to-stdstring\/<\/a>学习,下面的代码出现了一个问题
#include <string>
#include <iostream>
int main()
{
std::cout << "Pick 1 or 2: ";
int choice{};
std::cin >> choice;
std::cout << "Now enter your name: ";
std::string name{};
std::getline(std::cin, name); // note: no std::ws here
std::cout << "Hello, " << name << ", you picked " << choice << '\n';
return 0;
}
From the documentation<\/a> for std::getline():从 std::getline() 的
文档<\/a>中:
getline reads characters from an input stream and places them into a string:
1) Behaves as UnformattedInputFunction, except that input.gcount() is not affected. After constructing and checking the sentry object, performs the following:
1) Calls str.erase()
2) Extracts characters from input and appends them to str until one of the following occurs (checked in the order listed)
a) end-of-file condition on input, in which case, getline sets eofbit.
b) the next available input character is delim, as tested by Traits::eq(c, delim), in which case the delimiter character is extracted from input, but is not appended to str.
c) str.max_size() characters have been stored, in which case getline sets failbit and returns.
because there is still a \\n in the input buffer from the first read of choice<\/code> , you need to tell cin to ignore it.
因为在第一次读取的输入缓冲区中仍然有一个 \\n
choice<\/code> ,你需要告诉 cin 忽略它。
int choice{};
std::cin >> choice;
std::cin.ignore(); <<<=============
std::cout << "Now enter your name: ";
std::string name{};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.