我正在测试CodeBlocks中程序的字符串输出。这是代码:
#include <iostream>
#include <string>
using namespace std;
int main(){
string entry = "";
while(entry!="x"){
cout<<"Enter: ";
cin>>entry;
cout<<entry.substr(0,1)<<endl;
}
return 0;
}
但是,将结果打印好,好像是由空格和cout字符串" Enter"定界符,并以错误的订单的方式划定。什么是原因,我该如何解决这种情况?
Output:
Enter: P q r
P
Enter: q
Enter: r
Enter:
要读一行,不要使用 cin >> whatever
。当它遇到空格(空间,标签和纽文)时,它将停止阅读。使用std::getline()
:
getline(cin, entry);
现在这变成了:
assert(entry == "P q r");