尝试读取文件并将其输出到行中并计算字符数,行数和非空白字符数以及单词数。我想接近完成,但我无法弄清楚如何计算单词的数量。除了第一个字母之外,它还会切断每行的第一个字母。
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
int line_number = 0;
char words;
int number_of_spaces = 0;
int number_of_lines = 0;
int number_of_characters = 0;
int number_of_words = 0;
int count = 0;
char character;
string word;
int n = 0;
string line;
ifstream myFile;
string file;
cout <<"Enter file name: ";
getline(cin,file);
myFile.open(file.c_str());
char output[100];
if(myFile.is_open())
{
cout << " " << endl;
while( getline ( myFile, line ) )
{
line_number += 1;
cout << "Line: " << line_number << " ";
cout << line << endl;
number_of_characters += line.length();
for (int i = 0; i < line.length(); i++)
{
if(line[i] == ' ' || line[i] == '/t')
{
number_of_spaces++;
}
}
myFile.get(character);
if (character != ' ' || character != '/n')
{
number_of_lines += 1;
}
}
cout << " " << endl;
cout << number_of_characters << " characters, " << endl;
cout << number_of_characters - number_of_spaces << " non whitespace characters, " << endl;
cout << number_of_words << " words, " << endl;
cout << number_of_lines << " lines." << endl;
}
myFile.close();
system("Pause");
return 0;
}
答案 0 :(得分:1)
您可以使用&gt;&gt;逐字逐句阅读文件运营商。所以这段代码应该有效:
std::string word;
int counter = 0;
while (myFile >> word)
{
counter++;
}