[英]Getting unexpected numbers when reading integers from an array
我正在嘗試將整數從文件讀取到數組,但是當我嘗試讀取所述數組的元素時,我得到的數字與文件中的數字幾乎沒有關系。
#include <fstream>
#include <istream>
#include <iterator>
#include <string>
using namespace std;
//Main Function
int main()
{
//Declare variables and ask user for file names
string f1, f2;
int s1, s2, n = 0;
cout<<"Please enter the names of the files you would like to merge, file extensions included."<<endl;
cout<<"File 1 Name: ";
cin>>f1;
cout<<"File 2 Name: ";
cin>>f2;
//Opening files
ifstream fs1, fs2;
fs1.open(f1);
fs2.open(f2);
//Checking if both files exist
if (fs1 && fs2)
{
//Getting length of files
s1 = distance(istream_iterator<int>(fs1), istream_iterator<int>());
s2 = distance(istream_iterator<int>(fs2), istream_iterator<int>());
//Declaring arrays and writing values to them
int a1[s1], a2[s2];
while(!fs1.eof())
{
fs2 >> a2[n];
n++;
}
//Closing files
fs1.close();
fs2.close();
//Reading array
for (int i=0; i<s2; i++)
{
cout<<a2[i]<<endl;
}
}
//If the requested files do not exist
else
{
cout<<"No file exists with that name."<<endl;
}
}
我有兩個文本文件,file1.txt 和 file2.txt。 代碼打開文件,確定其中的整數個數,並創建一個包含整數個數的數組。
文件 1.txt: 45 69 87 3 9 32 11 9 6 66
文件 2.txt: 4
我在讀取 file1.txt (a1[]) 的數組時得到的 output 給出了非常意外的數字:
File 1 Name: file1.txt
File 2 Name: file2.txt
0
0
1878276352
6421656
4
6422016
3756032
48
16
4199922
如您所見,這不是我預期的 output。 file2.txt 僅包含數字 4,其輸出僅為16
我對 c++ 和一般編程有點陌生,所以你可能不得不忍受我。 有人看到我做錯了嗎?
我正在使用 Code::Blocks 和 gcc 是我的編譯器。 感謝您的時間。
測試,使用標准:
std::vector<int> read_file(std::string filename) {
int n;
std::vector<int> vector;
std::ifstream file;
file.open(filename);
if (file.is_open()) {
std::string line;
while (std::getline(file, line)) {
std::istringstream is(line);
while (is >> n) {
vector.push_back(n);
}
}
file.close();
}
return vector;
}
int main() {
std::vector<int> vector = read_file("file1.txt");
for (auto element: vector) {
std::cout << element << std::endl;
}
}
注: int a1[s1], a2[s2];
不符合 ISO C++ 標准。 有關詳細信息,請參閱為什么變長 arrays 不是 C++ 標准的一部分? 如果您在運行前無法知道數組的長度,請考慮使用std::vector
。
正如@user4581301 所說,您需要倒帶文件,因為std::distance()
會將文件讀到最后。
否則,您將已經在文件的末尾,並且您不會將任何數據讀入 arrays,這意味着您的 arrays 將持有未初始化的 memory。
這是一個解決方案:
// Rewind the files
fs1.clear();
fs2.clear();
fs1.seekg(0);
fs2.seekg(0);
// Read into array 1
for (n = 0; fs1 >> a1[n]; ++n) {}
// Read into array 2
for (n = 0; fs2 >> a2[n]; ++n) {}
seekg()
將 stream 中的 position 設置為給定的偏移量。 seekg(0)
重置為 stream 的開頭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.