【问题标题】:Printing integers from a file using an array使用数组从文件中打印整数
【发布时间】:2018-02-12 00:33:28
【问题描述】:

我刚刚开始学习 C++,但在使用程序时遇到了一些问题。它应该对外部文件中的数字进行排序。我已经成功地编写了排序算法,但是在处理外部文件时遇到了麻烦。我只是在一个单独的程序中测试一些东西,以了解 ifstream 之类的东西是如何工作的。一旦我更好地了解了它的工作原理,我应该能够弄清楚如何将它实现到我的程序中。

#include <iostream>
#include <fstream>
#include <string>
#include <vector>


int main() {
    using namespace std;


    int count;
    ifstream InFile;

    InFile.open ("unsorted.txt");

InFile >> count;
int numbers[count];      

for(int a = 0; a < count; a++)
    InFile >> numbers[a];
    cout << numbers << endl;
}

目前,此输出为 0x7ffc246c98e0 我不确定为什么会出现这种情况,我只是试图打印我的整数文件。谁能帮助解释我做错了什么?非常感谢。

【问题讨论】:

  • 可变长度数组不是标准 C++,请改用std::vector

标签: c++ arrays file ifstream


【解决方案1】:

当你这样做时

cout << numbers << endl;

打印指向数组第一个元素的指针。

你想要

cout << numbers[a] << '\n';

打印当前元素。


此外,如果这就是您的程序所做的全部,那么您实际上就不需要 数组。您只需要一个 int 变量:

int value;
for (int a = 0; a < count; ++a)
{
    InFile >> value;
    cout << value << '\n';
}

这也解决了可变长度数组的问题(因为没有)。

【讨论】:

  • 您好,感谢您的帮助!这是我第一次使用这种语言,非常感谢您帮助我!
【解决方案2】:

如果您打算使用 count 变量来计算文件大小或其他东西,那是您的代码出错的地方。您无法像尝试那样计算文件的长度。

while( getline ( InFile, line ) )
{
count += line.length();
}

也许,试试这样!!! 如果你使用

InFile>>count;

它会尝试将 InFile 流中的所有字符串存储到计数中,这不是有意的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 2021-04-02
    • 2015-06-04
    • 2012-08-19
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    相关资源
    最近更新 更多