【问题标题】:C++ File Output GarbageC++ 文件输出垃圾
【发布时间】:2018-09-12 04:31:03
【问题描述】:

这让我非常头疼,希望我能找到一些帮助。该程序应该读取 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;
}

【问题讨论】:

  • 这不是您编写代码来解决问题的方式...您了解数组了吗?
  • 第一行的错字。
  • 你得到了什么输出?
  • 输入文件的格式和准确的输出是什么?我无法用空格分隔的输入数字重现这个。
  • 随便猜测一下,您用来创建Lab12A.txt 的文本文件编辑器是否有可能在文件中插入了Unicode BOM 标记?然后,这可能导致标准库在尝试读取第一个数字时将输入流置于错误模式。

标签: c++ fileoutputstream garbage


【解决方案1】:

我只想添加评论,但由于我不能这样做,所以我将其作为答案。

我已复制您的文件并创建了一个文本文件以尝试重现您的问题。起初一切都很顺利(完全没有问题)。但是根据 Daniel Schepler 的评论,我将文件编码更改为 UTF8-BOM(您可以从 Notepad++ 编码菜单轻松完成)并再次尝试。我得到了与您发布的相同的值。我无法详细解释如何准确解释值,但我希望有更多经验的人在这里启发我们。

【讨论】:

  • 它只是导致未定义的行为(未初始化的变量),因为它无法成功读取任何值。因此,在这种情况下,您获得的确切值是没有意义的,并且可能会因优化设置或平台而异。
【解决方案2】:

首先,我要感谢所有查看并对此发表评论的人,我非常感谢,这个问题最终被归结为需要 .txt 文件的完整路径,而不是我最初发布的相对路径。无论出于何种原因,没有它,我的编译器无法识别该文件。似乎是一个愚蠢的错误,但我对此相对较新,所以那些肯定会吱吱作响。再次感谢大家!

【讨论】:

    【解决方案3】:

    您可以使用 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;
    }
    
    • 我不确定您所说的“最大的第五个整数”是什么意思。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-20
      • 1970-01-01
      相关资源
      最近更新 更多