如何制作std :: cin读取空格?

时间:2016-07-29 08:10:45

标签: c++ whitespace cin spaces

编辑:就像我说的那样,我知道之前已经问过这个问题,但是没有一个解决方案似乎适合我。请至少在关注它之前阅读帖子以及什么不是。

我知道之前在这个网站上已经问过这个问题了,但我似乎无法掌握如何让它与我的特定程序一起工作。从本质上讲,我正在创建一个小型的疯狂Libs类型的游戏,玩家必须输入某些东西才能使其融入故事。现在,如果用户输入中没有空格,这可以完美地运行,但是,第二个人抛出一个空格,程序可以跳过整个问题。这是我的代码:

    int main(){

int selection;

//News Report Variables
std::string nrfullname;
std::string nrcrime;
std::string nradjective;
std::string nrtown;
std::string nrpluralnoun;
std::string nrnounnotplace;
std::string nrverb;
std::string nradjective2;
std::string nrfullname2;
std::string nrnounnotplace2;

std::cout << "Welcome to Mad Libs! Please, pick a story!" << std::endl;
std::cout << "1. News Report" << std::endl;
std::cin >> selection;

if (selection == 1) {
    std::cout << "We need a full name of someone." << std::endl;
    std::cin << nrfullname;
    std::cout << "We need a crime." << std::endl;
    std::cin >> nrcrime;
    std::cout << "We need an adjective." << std::endl;
    std::cin >> nradjective;
    std::cout << "We need a town." << std::endl;
    std::cin >> nrtown;
    std::cout << "We need a plural noun." << std::endl;
    std::cin >> nrpluralnoun;
    std::cout << "We need a noun that is NOT a place." << std::endl;
    std::cin >> nrnounnotplace;
    std::cout << "We need a verb." << std::endl;
    std::cin >> nrverb;
    std::cout << "We need another adjective." << std::endl;
    std::cin >> nradjective2;
    std::cout << "We need a full name of someone else." << std::endl;
    std::cin >> nrfullname2;
    std::cout << "We need another noun that is NOT a place." << std::endl;
    std::cin >> nrnounnotplace2;
    }

正如您可能想象的那样,大多数人会选择在其中请求某人的全名(我肯定知道我会)。重点是,如果他们放入那个空间,它会跳过犯罪&#34;问题,然后简单地转向形容词问题。如果你们能告诉我如何让它正常工作会有所帮助,因为它一直在向我强调一点,而且我尝试的所有解决方案都使问题变得更糟或没有做任何事情来帮助修复它

谢谢, MTS

2 个答案:

答案 0 :(得分:1)

而不是std::cin << nrfullname,您只需使用std::getline(std::cin,nrfullname [, delim])

std::getline从输入流中提取字符并将结果存储在nrfullname中,直到下一个可选分隔符

答案 1 :(得分:0)

在std :: getline中使用并写:cin.getline(x,sizeof(x))

相关问题