私のプログラムで問題が発生しました。ここのプログラムは、C文字列へのポインタを引数として受け取り、文字列に含まれる単語の数と文字列の文字数を計算することになっています。これらの値は両方とも、メイン関数に戻されますが、グローバル変数は使用されません。その関数の後、私は、文字の数と単語の数を受け取り、単語ごとの平均文字数(または平均単語サイズ)をmain関数に返す別の関数を書くことになっています。私が書いた関数は、上記のすべてを行い、カウントから句読点やスペースを除外することになっています。私が持っている問題は、ユーザーとしてstringを入力してEnterキーを押すと、計算が行われないということです。私は終わりがなくなるまでenterを押し続けることができ、なぜそれが起こっているのか理解できません。どんな洞察も高く評価されています。私はポインタとC-Stringを初めて使用しています。あなたはCount_All
関数の実装では二重の無限ループを持ってユーザーが文字列を入力した後、プログラムが関数を計算していません
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
void Count_All(char*, int&, double&, int&); // Function prototype.
double Calc_Average (char*, int, int, double); // Function prototype.
int main()
{
const int size = 500;
char userString[size];
int Word = 0;
int Pun = 0;
double Total_Characters = 0;
double Average = 0.0;
cout << "Please enter a string of 500 or less characters: ";
cin.getline(userString, size);
cout << "\n";
Count_All (userString, Word, Total_Characters, Pun);
cout << "Number of words in the string: " << Word << "\n";
Average = Calc_Average (userString, Word, Pun, Total_Characters);
cout <<"\nAverage number of letters per word: "<< fixed <<
showpoint << setprecision(2) << Average << "\n" << endl;
cin.ignore(1);
return 0;
}
void Count_All (char*strptr, int &Word, double &Total_Characters, int &Pun) // Counts all characters and types.
{
int index = 0;
while (*strptr != '\0')
{
if ((isspace(*strptr)) || (ispunct(*strptr)))
{
while ((isspace(*strptr)) || (ispunct(*strptr)))
{
index++;
}
}
if ((isalnum(*strptr)) || (ispunct(*strptr)))
{
Word++;
while ((isalnum(*strptr))||(ispunct(*strptr)))
{
index++;
Total_Characters++; // Counting the total printable characters (including digits and punctuation).
if((ispunct(*strptr)))
{
Pun++; // Counting punctuation.
}
}
}
index++;
}
}
double Calc_Average(char*strptr, int Word, int Pun, double Total_Characters) // Calculates the average number of characters per words.
{
double Average = 0.0;
Total_Characters = Total_Characters - Pun; // Subtracting punctuation from all of the characters in the string (not including spaces).
Average = (Total_Characters/Word);
return Average;
}
印刷物は何ですか? –
文字列を入力しても何も表示されない場合、Enterキーを押すと新しい行が開始されます。 – Zjm4192