[英]strange array reading from file in C++
我試圖像這樣在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}
現在我真的很困惑。 為什么會這樣呢?
在此聲明中
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
而不是數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.