C ++ .eof.未读取文件的最后一个值
c++ .eof. Last value of file not read
我正在尝试将文件中的所有整数(最多可以有 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 个整数。
相关文章:
- 如何在写入文件时擦除最后一个逗号
- 我的C++程序只写入文本文件最后一个条目
- 读取最后一个整数文件C++
- 带有文件结束函数的 while 循环重复输出文件中的最后一个数字两次
- 输入文件中的第一个字符是输出文件中的最后一个字符,反之亦然
- SFML 将图像从 txt 文件加载到矢量中仅加载最后一个图像
- CMake 意外地将最后一个文件名预置到可执行文件中
- 当该应用程序中加速文件的最后一个修改时间发生更改时,如何重新启动应用程序
- C++ 输出在读取文本文件时跳过最后一个单词
- C++2d数组,用文件中最后一个元素值填充所有元素
- 将数据附加到 csv 文件,在最后一个条目之前而不是最后一个条目之后.C++
- 删除文件 C++ 中字符串中最后一个出现的字符
- 如何在QT中获取XML文件的最后一个节点
- 如何获取输入文件的行的第二个和最后一个字符,并在C++中组成数组
- 为什么最后一个写入文件的对象在cpp中重复,以及如何解决它
- 正在擦除文件中的最后一个输入
- 写入文件会复制最后一个条目
- Fstream不会保存文件中的最后一个单词,也不会从文件中读取
- 逐行计算文件:EOF 重复最后一个数字(不能使用中断)
- C++文件中的最后一个字符