这让我非常头疼,希望我能找到一些帮助。该程序应该读入一个包含 19 个整数的程序,然后将最小的(第 2 个整数)和最大的(第 5 个整数)输出到屏幕。但是,我所有的结果都会产生垃圾。
#include iostream>
#include <fstream>
#include <cstdlib>
using std::ifstream;
using std::ofstream;
using std::cout;
using std::endl;
//the goal of this program is to read in numbers from a file, then output the
//highest number and the lowest number to the screen
int main() {
ifstream fileInput;
int nOne, nTwo, nThree, nFour, nFive, nSix, nSeven, nEight, nNine, nTen, //there are 19 numbers in the file
nEleven, nTwelve, nThirteen, nFourteen, nFifteen, nSixteen, nSeventeen,
nEighteen, nNineteen;
cout << "Opening File" << endl;
fileInput.open("Lab12A.txt"); //the file is opened
if (fileInput.fail())
{
cout << "Input file opening failed. \n"; //the fail check doesnt pop up, so the file has been opened.
exit(1);
}
fileInput >> nOne >> nTwo >> nThree >> nFour >> nFive >> nSix >> nSeven >> nEight
>> nNine >> nTen >> nEleven >> nTwelve >> nThirteen >> nFourteen >> nFifteen //this is where they should be extracted
>> nSixteen >> nSeventeen >> nEighteen >> nNineteen;
cout << "The highest number is " << nTwo << endl;
cout << "The lowest number is " << nFive << endl;
fileInput.close();
system("pause");
return 0;
}
最佳答案
我只想添加评论,但由于我不能这样做,所以我将其作为答案。
我已经复制了你的文件并创建了一个文本文件来尝试重现你的问题。起初一切顺利(完全没有问题)。但是根据 Daniel Schepler 的评论,我将文件编码更改为 UTF8-BOM(您可以从 Notepad++ 编码菜单轻松完成)并再次尝试。我得到了你发布的相同值。具体如何解释值(value)观我无法给出更多的解释,但我希望有更多经验的人在这里启发我们。
关于C++ 文件输出垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49620050/