-1

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

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

2 回答 2

2

In the return_lines function, you declare count to be a local variable inside the loop. This means it will always be reset to zero each iteration, leading to lines also being set to zero all the time.

The other problem is that the istream::gcount function only returns the number of characters read from the last input operation, and as you don't do any input it will always return zero.

And there is no reason to use a double for the number of lines, as you will never have, say 12.3 lines in a file. Use int.


You should also check that the file operations succeed. While you do it correctly in return_lines, you don't check that the opening of the file was successful or not.

于 2013-06-15T08:35:54.540 回答
2

This function doesn't do what you describe it as. It returns "the number of characters read in the latest read operation (e.g. if you do in.getline(), then this line would return the length of that line).

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

    return characters;
}

To find out the size of the file, you need to seek to the end, get the position, and then seek back to the start. Although this is unreliable for text files on certain systems, because newline is two bytes in the file, and only counts as "one character" in C. If you want to count the characters in the file, and number of lines, then count the number of characters in each line (make your return_lines also take a parameter for number of characters it's read).

于 2013-06-15T08:39:51.670 回答