【问题标题】:strange array reading from file in C++在 C++ 中从文件中读取奇怪的数组
【发布时间】:2017-11-16 18:19:17
【问题描述】:

我试图在C++ 中初始化1.000.001 元素的数组,如下所示:int array[1000001]。我有 4GB 的 RAM,所以我猜问题是我的笔记本电脑无法容纳这么大的阵列,因为它的大小为 4 * 1000001 bytes。所以我决定尝试让它char(只是因为我想知道我的猜测是否正确)。我正在从文件中读取数组。这是我的代码:

#include <iostream>
#include <fstream>
#include <climits>

using namespace std;


int main()
{
    fstream in("C:\\Users\\HP\\Documents\\Visual Studio 2017\\Projects\\inputFile.in");
    if (!in)
    {
        cerr << "Can't open input file\n";
        return 1;
    }
    fstream out("outputFile.out", fstream::out);
    if (!out)
    {
        cerr << "Can't open output file\n";
        return 1;
    }

    int n;
    in >> n;
    int i;
    char array[100];
    for (i = 0; i < n; i++)
        in >> array[i];

    in.close();
    out.close();
}

输入:
5 45 5 4 3 12
我的数组是{4, 5, 5, 4, 3}。

对于输入: 5 12 3 4 5 45
我的数组是{1, 2, 3, 4, 5}

现在我真的很困惑。为什么会这样?

【问题讨论】:

  • 为什么要将整数读入 char 数组?

标签: c++ arrays input char


【解决方案1】:

在此声明中

in >> array[i];

使用了运算符

template<class charT, class traits>
basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>&, charT&);

模板参数charT被替换为模板类型参数char。

运算符从流中读取一个字符,跳过空白字符。

所以由于流包含以下字符序列

45 5 4 3 12

那么对于接线员的五次呼叫,将读取以下字符

4, 5, 5, 4, 3

空白字符将被跳过。

您可以将流读取为具有整数,例如

for (i = 0; i < n; i++)
{
    int value;
    in >> value;
    array[i] = value;
}

至于大整数数组的问题,当你应该将它声明为具有静态存储持续时间时,例如在任何函数之外声明它。或者您可以使用标准类 std::vector 代替数组。

【讨论】:

    猜你喜欢
    • 2022-11-07
    • 2017-01-19
    • 2023-02-23
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    相关资源
    最近更新 更多