C ++ .eof.未读取文件的最后一个值

c++ .eof. Last value of file not read

本文关键字:最后一个 文件 读取 eof      更新时间:2023-10-16

我正在尝试将文件中的所有整数(最多可以有 100 个整数(读取到一个数组中,并打印出输入的数字以及输入的数字数。我在使用".eof"时遇到问题。无论我尝试什么,都不会读取输入文件中的最后一个值。有人可以告诉我问题是什么吗?这是代码。

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
    {
    int bubble[100];
    int s = 0;
    int count = 0;
    string fileName;
    //int i = 0;
    for(int i = 0; i < 100; i++) bubble[i] = 0;
    cout << "Enter the name of a file of integers to be sorted " << endl;
    cin >> fileName;

   ifstream myfile (fileName);
    myfile >> s;
    //bubble[0] = s;

    while (! myfile.eof() )  //while the end of file is not reached
    {
        //myfile >> s;
        for(int i = 0; i < 100; i++)
        {
            //myfile >> s;
            if(! myfile.eof())
            {
                bubble[i] = s;
                myfile >> s;
            }
            else
            {
                bubble[i] = -1;
            } 
        } 

        //i++;
    }
    myfile.close();

    for(int i = 0; i < 100; i++)
    {
        if(bubble[i] != -1)
        {
            count ++;
        }
    }
   // cout << count;
    for(int i = 0; i < count; i++)
    {
        if(bubble[i] != -1)
    {

        if((i % 10 == 9) || (i== count-1))
        {
            cout << setw(4) << bubble[i] << endl;
        }
        else
        {
            cout << setw(4) << bubble[i] << " ";
        }
        //count ++;
    }
    }
    cout << "nnNumber of values in the input file: " << count << endl;
return 0;
}

输入:

100 94 59 83 7 11 92 76 37 89 74 59 65 79 49 89 89 75 64 82 15 74 82 68 92 61 33 95 91 82 89 64 43 93 86 65 72 40 42 90 81 62 90 89 35 81 48 33 94 81 76 86 67 70 100 80 83 78 96 58

输出:输入要排序的整数文件的名称bubble_input.txt 100 94 59 83 7 11 92 76 37 89 74 59 65 79 49 89 89 75 64 82 15 74 82 68 92 61 33 95 91 82 89 64 43 93 86 65 72 40 42 90 81 62 90 89 35 81 48 33 94 81 76 86 67 70 100 80 83 78 96

输入文件中的值数:59

(应为 60,58 应位于最后一个位置(

感谢您的任何帮助!

你在代码中所做的是(请原谅伪代码(:

save value of `s` in `bubble[i]`
read in an integer, saving it in the variable `s`,
repeat as long as we have something on the input

这样当你到达文件末尾时,最后一个变量仍然只存储在s中,你不会把它复制到bubble[i]。只需立即将其保存在数组中,即可解决您的问题。

编辑 - 我还注意到 - while 循环不像 if 那样工作。如果文件包含的整数超过 100 个,则将用后面的数字(可能还有 -1(覆盖前 100 个整数。