std::cin << varname 存在一些问题。
当用户在输入变量后键入“enter”时,cin 将只读取该变量,并将“enter”留给下一次读取。
当您将cin 与getline() 混合在一起时,您有时会吃掉“输入”,有时则不会。
一种解决方案是在cin 调用之后添加一个ignore 调用来吃掉“进入”
cin >> again;
std::cin.ignore();
第二种解决方案是使用 std::getline()。将 getline() 与 std::istringstream 结合起来通常是一个好习惯。这是使用 getline() 和 istringstream 解决此问题的另一种方法。解释见代码中的cmets。
#include <iostream>
#include <string.h>
#include <sstream>
int main()
{
std::string line;
std::string input;
std::istringstream instream;
do {
instream.clear(); // clear out old errors
std::cout << "Enter your phrase to find out how many characters it is: "
<< std::endl;
std::getline(std::cin, line);
instream.str(line); // Use line as the source for istringstream object
instream >> input; // Note, if more than one word was entered, this will
// only get the first word
if(instream.eof()) {
std::cout << "Length of input word: " << input.length() << std::endl;
} else {
std::cout << "Length of first inputted word: " << input.length() << std::endl;
}
std::cout << "Go again? (y/n) " << std::endl;
// The getline(std::cin, line) casts to bool when used in an `if` or `while` statement.
// Here, getline() will return true for valid inputs.
// Then, using '&&', we can check
// what was read to see if it was a "y" or "Y".
// Note, that line is a string, so we use double quotes around the "y"
} while (getline(std::cin, line) && (line == "y" || line == "Y"));
std::cout << "The end." << std::endl;
std::cin >> input; // pause program until last input.
}