ユーザーからの入力を受け取り、入力された単語の数を文字列に返すプログラムを作成する必要があります。ユーザー入力を配列に保存します char words[256];
私は関数と呼ばれる countWords
。配列をループし、スペースが検出されるとカウンターが増加します。 if(words[i] == " ")
ヌル文字に達すると、カウンターは停止します。それから戻ります 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] == " ")
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
回答:
回答№1は2あなたは、「ヌル文字に到達したときにループを停止していません。あなた」は、内部のヌル文字のみをテストしています。 if(isspace(words[i]))
ブロックしますが、文字がスペースの場合はnullターミネータにすることもできません。その結果、入力の終わりを超えて読み取り、文字列の初期化されていない部分のスペースをカウントします。
int countWords(char words[]){
int nSpaces = 0;
for (int i=0; i<256 && words[i] != " "; i++){
if(isspace(words[i])){
nSpaces++;
}
}
// The number of words = the number of spaces + 1
return nSpaces + 1;
}
回答№2の場合は0
isspace
改行(n)、タブ(t)、v、f、rをカウントします。
おそらく、空白のみが必要ですか? 「」と「t」のみを確認してください。