我是 C++ 和一般编码的新手,在我的一项作业中遇到了一些问题。我只是在寻找一些输入,希望能解释为什么我的代码不起作用。
我正在尝试获取用户的输入并使用 cin.get()
函数来计算该字符串中的所有字符。我这样做是因为我想确定字符串中每个单词的字母。现在我的问题是无法正确打印结果。
我的问题是:为什么当我试图确定我的变量 chr
是否是一个 '\n' 字符时我得不到结果? chr
是保存由 cin.get()
函数读取的当前字符值的变量)是一个 '\n'
.
当 chr
的当前值为 时,我希望能够更新函数
或换句话说,字符串的末尾。countWordsByLegth()
的参数(word1、word2.....)\n'
例如,以下代码将不会运行,这是我知道如何为不包含空格的字符串(单字串)更新参数的唯一方法:
if (counter == 5 && chr == '\n')
{
++word5;
counter =0;
}
这是我的代码供引用。函数 isWhitespace()
只是确定字符是否为以下之一 '\n'
, '\r'
, '\t'
):
while (cin.get(chr) && chr != '\n')
{
counter++;
if (isWhitespace(chr))
{
--counter;
//test = true;
}
if (counter == 5 && chr == '\n')
{
++word5;
counter =0;
}
if (counter == 4 && chr =='\n')
{
++word4;
counter =0;
}
if (counter == 3 && chr =='\n')
{
++word3;
counter =0;
}
if (counter == 2 && chr == '\n')
{
++word2;
counter =0;
}
if (counter ==1 && chr == '\n')
{
++word1;
counter =0;
}
cout << counter << endl; // Test code {delete later}
}
cout << "This is the total of word5: " << word5 << endl;
最佳答案
您可以使用 std::string.length()
获取字符串中的字符数。
length()
函数返回字符串中的字符数。
#include <iostream>
#include <string>
int main()
{
std::string s;
s = "test";
std::cout << "The string has " << s.length() << " letters!";
}
http://www.cplusplus.com/reference/string/string/在这里您可以阅读有关可以与字符串一起使用的不同功能的信息。
关于c++ - 在 C++ 中确定字符串的每个单词中的字母数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58372281/