我想从标准输入中读取一个单词,然后在C++中查找它的长度。我目前正在使用:C++:从标准输入中读取一个单词并找出它的长度?
char str[80];
cout << "Enter your word: " << endl;
scanf("%s", str);
,但不能得到读字的长度
如何做到这一点?
感谢。
我想从标准输入中读取一个单词,然后在C++中查找它的长度。我目前正在使用:C++:从标准输入中读取一个单词并找出它的长度?
char str[80];
cout << "Enter your word: " << endl;
scanf("%s", str);
,但不能得到读字的长度
如何做到这一点?
感谢。
看看你如何使用cout
写入标准输出?以一种并行的方式,在现代C++中,我们使用cin
从标准输入读取。另外,在现代C++中,我们有一个真正的字符串类型,名为std::string
,我们用它来存储字符串。它来自<string>
标题,它可以告诉我们它自己的长度。
这样:
string str;
cout << "Enter your word: " << endl;
cin >> str;
int len = str.length();
您可以使用strlen获取字符串的长度。
int len = strlen(str);
关于std:“cin >> str”的“不太好”是它们停在空格处“”。我们应该使用“cin.getline”来代替。
char name[256];
cout << "Enter your name: ";
cin.getline (name,256);
为什么在使用C++ iostream工具时使用C stdio工具? `std :: string s; std :: cin >> s; unsigned len = s.length();` – 2010-12-09 04:40:28