#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;
}
答案 0 :(得分:1)
我希望只添加一条评论,但由于我不能这样做,我将其留作答案。
我复制了您的文件并创建了一个文本文件,以尝试重现您的问题。起初一切都很顺利(根本没问题)。但是通过 Daniel Schepler 的评论,我将文件编码更改为 UTF8-BOM (您可以通过Notepad ++编码菜单轻松完成)并再次尝试。我发布了相同的值。我无法更准确地解释如何解释价值观,但我希望有更多经验的人在这里启发我们。
答案 1 :(得分:1)
首先,我要感谢所有看过并对此发表评论的人,我非常感谢,问题最终归结为需要.txt文件的完整路径,而不是我最初发布的相对路径。出于某种原因,没有它我的编译器无法识别该文件。看起来像是一个愚蠢的错误,但我对此相对较新,所以那些肯定会发出吱吱声。再次感谢大家!
答案 2 :(得分:0)
您可以使用类std::vector
推送值然后对容器进行排序,最后打印第二个和第五个元素:
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
int main(){
std::ifstream in("test.txt");
std::vector<int> vecInt;
int value;
while(in >> value)
vecInt.push_back(value);
in.close();
std::sort(vecInt.begin(), vecInt.end());
// second value is at index 1 and fifth value is at index 4
for(auto i(0); i != vecInt.size(); ++i)
if(i == 1 || i == 4)
std::cout << vecInt[i] << std::endl;
std::cout << std::endl << std::endl;
return 0;
}