[英]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.