我差不多完成了一个程序但是我需要设置它以便它会保持循环并询问文件名,直到给出一个无效的名字,然后它会立即退出并结束程序但我正在做某事错了,无法弄清楚它有什么问题,因为它只会经历一次循环......
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
int line_number = 0;
char words;
int number_of_characters = 0;
int number_of_spaces = 0;
int number_of_words = 0;
string line;
ifstream myFile;
string file;
cout <<"Enter file name: ";
getline(cin,file);
myFile.open(file.c_str());
char output[100];
while(myFile.good())
{
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.clear();
myFile.seekg(0,myFile.beg);
while(myFile >> line)
{
number_of_words++;
}
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 << line_number << " lines." << endl;
cout << " " << endl;
}
}
cout << endl << "Invalid file name." << endl << "Terminating..." << endl << endl;
myFile.close();
system("Pause");
return 0;
}
答案 0 :(得分:0)
我在代码中看到的主要问题是您没有将代码放在while
循环中读取文件名。
您还有其他错误,很可能是拼写错误。您在
行中使用的是'/t'
而不是'\t'
if(line[i] == ' ' || line[i] == '/t')
更重要的是,您可以将main
中的代码划分为以下不同的操作。
您可以定义main
以反映这些操作。
int main()
{
std::string file;
while ( is_good_file(file = get_filename()) )
{
process_file(file);
}
cout << endl << "Invalid file name." << endl << "Terminating..." << endl << endl;
return 0;
}
然后,定义三个函数。
std::string get_filename()
{
std::string file;
cout <<"Enter file name: ";
getline(cin,file);
return file;
}
bool is_good_file(std::string const& file)
{
std::ifstream fstr(file);
return (fstr);
}
void process_file(std::string const& file)
{
int line_number = 0;
int number_of_characters = 0;
int number_of_spaces = 0;
int number_of_words = 0;
string line;
std::ifstream fstr(file);
while( getline ( fstr, line ) )
{
line_number += 1;
cout << "Line: " << line_number << " ";
cout << line << endl;
number_of_characters += line.length();
for (size_t i = 0; i < line.length(); i++)
{
if(line[i] == ' ' || line[i] == '\t')
{
number_of_spaces++;
}
}
}
fstr.clear();
fstr.seekg(0,fstr.beg);
while(fstr >> line)
{
number_of_words++;
}
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 << line_number << " lines." << endl;
cout << " " << endl;
}
考虑高级操作可以帮助您组织代码。它还可以帮助您隔离错误并更轻松地修复它们。