我在该程序中有一个while循环。我希望它能以与用户输入中一样多的字母来运行程序。当用户输入中没有空格时,此方法有效,但是当用户输入中没有空格时,它将停止计数字母的数量。这是完整的代码:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> cons = {"b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y"};
vector<string> vowel = {"a", "e", "i", "o", "u"};
int count_val = 0;
string user_translate;
int main(){
cout << "Enter the word you want translated: ";
cin >> user_translate;
while(count_val < user_translate.length()){
if(user_translate[count_val] == ' '){
cout << "No sentences!";
}
cout << user_translate.length();
++count_val;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我不确定为什么.length()无法正常工作。我做错什么了吗,还有另一种方法可以用来查找添加空格的字母数。谢谢。
string str;
std::getline(cin,str);
int len = str.length();
Run Code Online (Sandbox Code Playgroud)
这样,您也可以获得具有空格的字符串的实际长度。
std::cin>> str; //一旦字符串中出现第一个空格,将不会读取读取的字符串。
就像如果你的字符串想输入一个字符串My name is Mama使用std::cin>>str;仅str = "My"将被保存。
| 归档时间: |
|
| 查看次数: |
4354 次 |
| 最近记录: |