C++ 输入一个整数,然后输入一个带空格c++;

C++ 输入一个整数,然后输入一个带空格c++;,c++,C++,如何将一个整数转换为“带空格”的字符串 这是我的密码 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

如何将一个整数转换为“带空格”的字符串 这是我的密码

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  
intx;字符串s;

cout您可能遇到的问题是,
cin>>x
只读取您键入的数字,而不读取下面的换行符。然后,当您执行
cin>>s
读取字符串时,输入处理器会看到换行符并仅返回空字符串


解决方案是使用一个设计用于读取整行输入的函数,例如
std::getline
。不要使用提取运算符进行交互式输入。

读取带空格的字符串

但是 注意
>>
碰到分隔符时会发生什么。它停止并在流中留下分隔符。这不是问题,只要您只使用
>
,因为
>
将丢弃所有空白
std::getline
将捕获该空白,一个常见的用例是

user types in number and hits enter
user types in string and hits enter
那么会发生什么呢
>>
提取数字,当数字出现空白时停止。这将通过在流中按enter键将行的结尾放入流中<代码>std::getline
出现时,它看到的第一件事是。。。下线
std::getline
存储一个空字符串并立即返回。现在,程序处理一个空字符串,仍然希望输入字符串的用户输入一个字符串,该字符串将由将来的某个读取操作读取,可能会将输入流放入错误案例中,并肯定会给用户一个惊喜


一种常见的解决方案是,在提示用户输入并调用
std::getline

为什么#include?您尝试了什么?还有,为什么每个人都要包括
??或者任何其他的whatever@GregHewgill哦,基本上是当你懒得包含相应的标准头的时候。有道理。@AhmedElectrony如果你用谷歌搜索“如何输入字符串c++”,这个问题本身就很容易解决。事实上,在int之前有一个int并不重要。