[英]reading from a text file and printing every number right away gives different output than printing after reading all the file
所以我想從文件中讀取數字,文件看起來像這樣:
8
9 5 7 -5 13 -4 11
7 5 -3 12 -5 17 -3
25 7 12 -3 5 -5 7 -5 3
14 5 12 -3 10 -7 8
5 1 -40
33 5 15 -5 9 -3 8
11 5 -12 8 -5 12 -3
13 5 3 -4 25 -5 3
我需要所有數字,這些數字不在第一行,也不在該行的第一位,這是我的代碼:
#include <iostream>
#include <fstream>
using namespace std;
int times[99];
int n, k, t;
int main()
{
ifstream file("U1.txt");
file >> n;
for (int i = 0; i < n; i++)
{
file >> k >> t;
for (int j = 0; j < t; j++)
{
file >> times[j];
cout << times[j] << " ";
}
cout << endl;
}
for (int i = 0; i < 99; i++)
{
cout << times[i] << " ";
}
return 0;
}
在閱讀時輸出每個數字都會得到我想要的:
7 -5 13 -4 11
-3 12 -5 17 -3
12 -3 5 -5 7 -5 3
12 -3 10 -7 8
-40
15 -5 9 -3 8
-12 8 -5 12 -3
3 -4 25 -5 3
由於某種原因,我閱讀完所有內容后的輸出是這樣的(我不介意0,我知道它們為什么在這里):
3 -4 25 -5 3 -5 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
每次啟動內部循環時,都將j重置為0,因此在讀取每一行后,您將覆蓋先前寫入數組的內容。 這將導致數組僅包含文件的最后一行。
您可能應該創建另一個變量,在外部循環開始之前對其進行一次初始化,然后在內部循環內部對其進行遞增。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.