下面的代碼應該算作:從文本文件中讀取的行,字符和單詞。從文件輸入計算行數?
輸入文本文件:
This is a line.
This is another one.
所需的輸出是:
Words: 8
Chars: 36
Lines: 2
然而,字數統計出來爲0,如果我改變那麼它的線條和文字出來爲0,字數是正確的。我得到這個:
Words: 0
Chars: 36
Lines: 2
這是我的代碼:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ifstream inFile;
string fileName;
cout << "Please enter the file name " << endl;
getline(cin,fileName);
inFile.open(fileName.c_str());
string line;
string chars;
int number_of_lines = 0;
int number_of_chars = 0;
while(getline(inFile, line))
{
number_of_lines++;
number_of_chars += line.length();
}
string words;
int number_of_words = 0;
while (inFile >> words)
{
number_of_words++;
}
cout << "Words: " << number_of_words <<"" << endl;
cout << "Chars: " << number_of_chars <<"" << endl;
cout << "Lines: " << number_of_lines <<"" << endl;
return 0;
}
任何指導,將不勝感激。
'while(getline(inFile,line))'吃了整個文件。在'while(inFile >> words)之前倒帶或關閉並重新打開' – user4581301
您需要1.關閉並重新打開文件2.使用'stringstream'查找每行中有多少個單詞。 – crashmstr
從長遠來看,使用'stringstream'來獲取每行文字可能更有用。 – crashmstr