c++ - 如何获取不以空格结尾的字符串的输入?

标签 c++ string input cout getline

<分区>

#include <iostream>
#include<string>
#include<vector>
#include<algorithm>


using namespace std;

int main()
{

 vector<string>Games;
 vector<string>::iterator iter;
 string command;
 string name;


cin>>command;
if(command=="add"){
    cout<<"You have choosen to add a game to your backlog.\n";
    cout<<"Enter the name of the Video Game\n";
    getline(cin,name); 
    Games.push_back(name);
    cout<<"The Game has been added\n";
}

是的,我知道这已存档。而且我知道你应该使用 getline() 函数将 cin 和字符串的名称传递给函数来保存字符,但是当我在键入“添加”命令后编译并运行它时,然后该行 getline(cin,name) 被跳过,我无法输入任何内容。

最佳答案

之前

getline(cin,name); 

使用

cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

要使用此语句,您需要包含 header <limits>

关于c++ - 如何获取不以空格结尾的字符串的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21150909/

相关文章:

c++ - 在包装类的枚举中定义静态 constexpr 值

c++ - 缩小窗口时 EMF 质量会降低,但在窗口尺寸较高时会很好

c++ - 将成员函数指针转换为具有多个参数的标准 C 函数

javascript - 移动输入无法以编程方式更新

C: gets() 跳过第一个输入

java - 读取微调器输入

c++ - 在 xml 中存储 C++ 二进制输出

java - 按空格分隔字符串

c++ - 在 C++ 中拆分字符串的更快方法

c - 从一个字符串中删除另一个字符串中的字符的函数