我遇到了一個與我的程序有關的問題。這裏的程序應該接受一個指向C字符串的指針作爲參數,並計算字符串中包含的單詞數以及字符串中的字母數。這兩個值都應該傳回主函數,但不使用全局變量。在該函數之後,我應該編寫另一個接受字母數量和字數的函數,並將每個字的平均字母數(或平均字大小)發送回主函數。我寫的功能應該完成上述所有功能,並且還可以從計數中排除標點符號和空格。我遇到的問題是,當我以用戶身份輸入字符串並按下回車鍵時,不會進行任何計算。我可以繼續按下直到沒有結束,我無法弄清楚爲什麼會發生。任何洞察力將不勝感激,我是新的指針和C字符串。用戶輸入字符串後,程序不計算函數
這裏是我的代碼:
#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;
}
什麼打印? –
輸入字符串後,沒有任何東西被打印出來,你按下回車鍵,它只是開始新的行。 – Zjm4192