我需要制作一个程序来接受用户的输入,然后将输入的单词数返回到字符串中。我将用户输入存储在数组中,char words[256];
我有一个名为countWords
. 它遍历数组,如果遇到空格,他的计数器就会增加。if(words[i] == '\0')
如果达到空字符,则计数器停止。然后它返回nSpaces + 1
到第一个单词。
但我的输出似乎产生了字符串中的字符数。这怎么能解决。
#include <iostream>
#include <cstdlib>
using namespace std;
//Function Prototype
int countWords(char words[]);
int main(){
char words[256];
cout << "Enter a sentence: ";
cin.getline(words, 256);
int word_num = countWords(words);
cout << "The number of words in a string is: " << word_num << endl;
system("PAUSE");
return 0;
}
int countWords(char words[]){
int nSpaces = 0;
//unsigned int i = 0;
/*while(isspace(words[i])){
i++;
}*/
for (int i=0; i<256; i++){
if(isspace(words[i])){
nSpaces++;
// Skip over duplicate spaces & if a NULL character is found, we're at the end of the string
//while(isspace(words[i++]))
if(words[i] == '\0')
nSpaces--;
}
}
// The number of words = the number of spaces + 1
return nSpaces + 1;
}
输出是:
Enter a sentence: Yury Stanev
The number of words in a string is: 7