我试图找出一个字符串的长度。这工作并输出14
:
#include <iostream>
#include <string>
using namespace std;
int main(){
string str = "this is sparta";
cout << str.length() << endl;
}
但是,这失败了:
#include <iostream>
#include <string>
using namespace std;
int main(){
string str;
cin >> str;
cout << str.length() << endl;
}
当我输入句子this is sparta
并按回车键时,我会得到4
长度。
我究竟做错了什么?
那是因为cin
停在空白处。如果您想阅读所有单词,则需要循环:
int main() {
string str;
while (cin >> str) {
cout << str << " --> " << str.length() << endl;
}
}
或者,如果您想一次全部使用它们,则需要使用getline
:
int main() {
string str;
while (getline(cin, str)) {
cout << str << " --> " << str.length() << endl;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句