程序不能读取文件

Program not reading file in

本文关键字:文件 读取 不能读 不能 程序      更新时间:2023-10-16

当我运行它并键入文件名时,我的程序似乎没有在文件中读取。会不会是因为它不知道去哪里找呢?此外,我的函数返回文件中的行数只返回它出现的内存地址。

#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;
}

这个函数并不像你描述的那样。它返回在最近一次读取操作中读取的字符数(例如,如果执行in.getline(),则这一行将返回该行的长度)。

int return_Characters (ifstream&在){Int characters = in.gcount();

    return characters;
}

要找出文件的大小,您需要查找到末尾,得到位置,然后查找到开始处。虽然这对于某些系统上的文本文件来说是不可靠的,因为newline在文件中是两个字节,并且在c中只算作"一个字符"。如果您想计算文件中的字符和行数,那么计算每行中的字符数(让您的return_lines也接受它读取的字符数的参数)。

return_lines函数中,将count声明为循环中的局部变量。这意味着每次迭代它都会被重置为零,导致lines也一直被设置为零。

另一个问题是istream::gcount函数只返回从上次输入操作中读取的字符数,并且由于您不进行任何输入,它将始终返回零。

并且没有理由使用double来表示行数,因为您永远不会在文件中使用,例如12.3行。使用int .


您还应该检查文件操作是否成功。当您在return_lines中正确地执行此操作时,您不会检查文件打开是否成功。