我有以下代码提示用户输入他们的名字和状态:
#include <iostream>
#include <string>
int main()
{
std::string name;
std::string state;
if (std::cin >> name && std::getline(std::cin, state))
{
std::cout << "Your name is " << name << " and you live in " << state;
}
}
Run Code Online (Sandbox Code Playgroud)
我发现该名称已被成功提取,但不是州.这是输入和结果输出:
Run Code Online (Sandbox Code Playgroud)Input: "John" "New Hampshire" Output: "Your name is John and you live in "
为什么输出中省略了状态名称?我给出了正确的输入,但代码忽略了它.为什么会这样?
我从C++中的一个函数调用一个函数,该函数的getline(cin,name)名称是一个字符串.第一次循环,程序不等待输入.它将在所有其他通过循环.有什么想法吗?
void getName (string& name)
{
int nameLen;
do{
cout << "Enter the last Name of the resident." << endl << endl
<< "There should not be any spaces and no more than 15"
<< " characters in the name." << endl;
getline(cin,name);
cout << endl;
nameLen = name.length();// set len to number of characters input
cout << "last" << name << endl;
}
while (nameLen < LastNameLength);
return;
}
Run Code Online (Sandbox Code Playgroud)