【问题标题】:How to get input to a string that does not terminate with a space? [duplicate]如何获取不以空格结尾的字符串的输入? [复制]
【发布时间】:2014-01-16 00:04:21
【问题描述】:
#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 和字符串名称传递给函数来保存字符,但是当我在键入“add”命令后编译并运行它时,则该行 getline(cin,name) 被跳过,我无法输入任何内容。

【问题讨论】:

  • 在网站上搜索“getline skipped”。我保证你会找到很多。或者,查看右侧的相关链接。它们看起来真的很相关。
  • 知道了,谢谢,在我发帖之前我真的应该多搜索一下。原来我必须包括行 cin.ignore();在用户输入名称之前。有人能解释一下这条线的作用吗?
  • 好的,我明白了,谢谢

标签: c++ string input cout getline


【解决方案1】:

之前

getline(cin,name); 

使用

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

要使用此语句,您需要包含标题&lt;limits&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    相关资源
    最近更新 更多