当我运行它并键入文件名时,下面的程序似乎没有读取文件。难道是因为它不知道去哪里寻找它们?此外,我返回文件中行数的函数只返回它出现的内存地址。
#include <iostream>
#include <fstream>
#include<string>
using namespace std;
函数返回输入的 txt 文件中的字符数:
int return_Characters(ifstream& in)
{
int characters = in.gcount();
return characters;
}
假设获取 txt 文件中的行数并将该数字作为双精度返回的函数:
double return_lines(ifstream& in)
{
string name;
double lines = 0;
while(getline(in, name) ){
int count = 0;
lines = count++;
}
return lines;
}
主功能:
int main()
{
string file_name;
ifstream input_file;
cout << "Please enter the name of your file" << endl;
do 循环读取用户输入的 file_name 字符串并运行函数以获取用户输入的 txt 文件中的字符和行数:
do {
getline(cin, file_name);
cout << "checking" << ' ' << file_name << endl;
input_file.open(file_name);
int count_characters = return_Characters(input_file);
cout << "the number of characters is equal to " << count_characters << '\n';
double count_lines = return_lines(input_file);
cout << "the number of lines in the file is equal to" << return_lines << '\n';
input_file.close();
}while(!file_name.empty());
cout << "there was an error oepning your file. The program will not exit" << endl;
system("Pause");
return 0;
}