【发布时间】:2015-04-25 21:49:30
【问题描述】:
如何从每行的字符串中打印一个单词,并在其旁边显示字符数以及字符的平均值?我想使用字符串成员函数将对象转换为 c 字符串。 countWords 函数接受 c 字符串并返回一个 int。该函数假设读取每个单词及其长度,包括字符的平均值。我已经完成了字符串中有多少单词,除了我不知道如何继续其余的。
例如:超级大炮男孩
超级5
伟大的 5
大炮 6
男孩 4
平均字符数:5
这是我目前的程序:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int countWords(char *sentence);
int main()
{
const int size=80;
char word[size];
double average=0;
cout<<"Enter words less than " <<size-1<<" characters."<<endl;
cin.getline(word, size);
cout <<"There are "<<countWords(word)<<" words in the sentence."<<endl;
return 0;
}
int countWords(char *sentence)
{
int words= 1;
while(*sentence != '\0')
{
if(*sentence == ' ')
words++;
sentence++;
}
return words;
}
【问题讨论】:
-
使用索引和
for循环遍历字符串可能比指针算法更简洁易用。 -
@Carcigenicate 使用
std::string并通过for each loop对其进行迭代更加容易。 -
@NO_NAME 我想他说他需要使用 c 字符串。
-
@Carcigenicate 对不起。
#include <string>把我弄糊涂了。 -
而不是测试 *sentence == ' ' 你应该测试 isspace(*sentence) 。此外,您可能需要考虑使用标点符号函数 ispunct () 。两者在 ctype.h 中都有原型