CodeBlocks 字符串输出分隔
CodeBlocks string output delimitered
我正在为 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;
}
然而,打印结果就好像它是由 space 分隔的,而 cout 字符串 "Enter" 的顺序错误,就好像它被窃听了一样。可能是什么原因,我该如何解决这种情况?
Output:
Enter: P q r
P
Enter: q
Enter: r
Enter:
要阅读整行,请不要使用 cin >> whatever
。遇到白色space(space、制表符和换行符)就会停止读取。使用 std::getline()
:
getline(cin, entry);
现在这变成了现实:
assert(entry == "P q r");
我正在为 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;
}
然而,打印结果就好像它是由 space 分隔的,而 cout 字符串 "Enter" 的顺序错误,就好像它被窃听了一样。可能是什么原因,我该如何解决这种情况?
Output:
Enter: P q r
P
Enter: q
Enter: r
Enter:
要阅读整行,请不要使用 cin >> whatever
。遇到白色space(space、制表符和换行符)就会停止读取。使用 std::getline()
:
getline(cin, entry);
现在这变成了现实:
assert(entry == "P q r");