简体   繁体   English

输入一个整数,然后输入一个带有空格的字符串 c++

[英]Entering an Integer then a string with spaces c++

How can i cin an integer then a string "with spaces" this is my code我怎么能 cin 一个整数然后一个字符串“带空格”这是我的代码

int x;string s;
    cout<<"Enter Integer"<<endl;
    cin>>x;
    cout<<"Enter the string with spaces"<<endl;
    //if i used cin>>s here then it will not read all the text because it has spaces 
    // is i used getline(cin,s); then it will not read any thing  

The problem you are likely having is that the cin >> x reads only the digits of the number you type, and not the following newline.您可能遇到的问题是cin >> x读取您键入的数字的数字,而不是以下换行符。 Then, when you do a cin >> s to read a string, the input processor sees the newline and returns only an empty string.然后,当您执行cin >> s读取字符串时,输入处理器会看到换行符并仅返回一个空字符串。

The solution is to use a function that is designed to read whole lines of input, such as std::getline .解决方案是使用旨在读取整行输入的函数,例如std::getline Do not use the extraction operator >> for interactive input.不要将提取运算符>>用于交互式输入。

To read a string with spaces use std::getline .要读取带空格的字符串,请使用std::getline

But!但!

Pay attention to what happens with >> when it hits a delimiter.注意当>>遇到分隔符时会发生什么。 It stops and leaves the delimiter int he stream.它停止并在流中留下分隔符。 This is not a problem so long as you only use >> as >> will discard all of the whitespace.只要您只使用>>因为>>将丢弃所有空格,这不是问题。 std::getline will capture that whitespace, and a common usecase is std::getline将捕获该空格,一个常见的用例是

user types in number and hits enter
user types in string and hits enter

So what happens?那么会发生什么? >> extracts the number and stops when it hits whitespace. >>提取数字并在遇到空格时停止。 This leaves the end of line put in the stream by pressing enter in the stream.通过在流中按回车键,将行尾放入流中。 std::getline comes along and the first thing it sees is... end of line. std::getline出现,它看到的第一件事是......行尾。 std::getline stores an empty string and immediately returns. std::getline存储一个空字符串并立即返回。 Now the program processes an empty string and the user, still expecting to type in a string enters a string that will be read by some future read, possibly putting the input stream into an error case and certainly giving the user a surprise.现在程序处理一个空字符串,并且仍然期望输入字符串的用户输入了一个将由将来读取的字符串,这可能会将输入流放入错误案例中,并且肯定会给用户带来惊喜。

A common solution is to use ignore(numeric_limits<streamsize>::max(), '\\n');一个常见的解决方案是使用ignore(numeric_limits<streamsize>::max(), '\\n'); to consume any data still in the stream up to and including the end of line before prompting the user for input and calling std::getline .在提示用户输入和调用std::getline之前,使用流中的任何数据,直到并包括行尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM