-1
這個程序應該從由用戶提供的文本文件讀出的段,然後將每個線存儲在參差不齊的字符數組和計算單詞和線的總數量的行然後顯示結果。如何計算單詞和被輸入作爲一個CString陣列
我想不通爲什麼行的數量不斷給我的3 爲什麼單詞的數量總是缺少2個字的結果。
請幫助,並記住,我不是專業的,剛開始學習C++最近。
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
ifstream infile;//declarations
char filename[45];
char **data = 0;
char **temp = 0;
char *str = 0;
char buffer[500], c;
int numoflines = 0, numofwords = 0;
cout << "Please enter filename: ";//prompt user to enter filename
cin >> filename;
infile.open(filename);//open file
if (!infile)//check if file was successfully opened
{
cout << "File was not successfully opened" << endl << endl;//display error message
return 0;
} //end of if
data = new char*[numoflines];
while (!infile.eof())
{
temp = new char*[numoflines + 1];
for (int i = 0; i < numoflines; i++)
{
infile.getline(buffer, 500);//read line
for (int i = 0; i < strlen(buffer); i++)//count number of words in line
{
c = buffer[i];
if (isspace(c))
numofwords++;
}
str = new char[strlen(buffer) + 1];//allocate a dynamic array
strcpy(str, buffer);
data[i] = str;
temp[i] = data[i];
}//end of for
infile.getline(buffer, 500);
for (int i = 0; i < strlen(buffer); i++)//count number of words in line
{
c = buffer[i];
if (isspace(c))
numofwords++;
}
temp[numoflines] = new char[strlen(buffer) + 1];
strcpy(temp[numoflines], buffer);
delete[] data;
data = temp;
numoflines++;
}
cout << "Number of words: " << numofwords << endl;
cout << "Number of lines: " << numoflines << endl;
return 0;
}
對於'ifstream :: getLine',默認分隔符是'\ n'。我猜你的文本包含3段,它只包含3個'\ n'字符,這就是爲什麼你得到3作爲行數。 – sanastasiadis
對於單詞數量,我猜問題是你檢查了空格字符。也許檢查空間「或」時期「。會更好。 – sanastasiadis
考慮「這個字符串」。它有兩個詞,但有很多空格。還要考慮「這個字符串」 - 它有兩個字,只有一個空格。最後「這是怎麼回事」?這是一個字還是三個字? (哦,不要忘記「」 - 這是零字)。 –