gpt4 book ai didi

c++ - 如何查找输入文件的大小

转载 作者:行者123 更新时间:2023-11-30 03:44:41 26 4
gpt4 key购买 nike

我编写了代码以从输入文件中获取数据(它只是一列 1 和 0)并将其转换为任意多的 32 位数字。当我知道我的输入文件中有多少数字时,这很好用。我正在尝试修改它,以便它适用于我不知道大小的不同输入文件,这就是我遇到问题的地方我的输入文件是 rad。我试过:

int x=0;
while(!rad.eof()) {
x++;
}
cout << x;

什么都不返回,

while(!rad.eof()) {
rad >> x;
cout << x << endl;
}

返回大量相同的大数

while(!rad.eof()) {
rad >> x;
cerr << x << endl;
}

它返回很多零

当我知道输入文件的大小时有效的代码是:

/*const int m=32,n=40000; //n isnt 40000, change it so that its the size of    radioactivedata
int a[n]; // variable to hold each number as it is read from file
int i=0,j=0; //define variables
for ( i=0 ; i<n ; i++ ) a[i]=0;
for ( i=0 ; i<n ; i++ ); rad >> a[i]; //read numbers from rad into array with (>>) operator

unsigned long Num=0;
while(j<n){
i = 0; //reinitialize i and Num
Num = 0;
while ( i<m ){
Num = Num + (a[j])*pow(2.,i);
i++;
j++;
}

cout << j/m << "\t" << Num << endl;
out << j/m << "\t" << Num << endl;
}*/

如有任何帮助,我们将不胜感激,请使用通俗易懂的语言。

最佳答案

假设 rad 是一个 std::ifstream你可以使用 seekg()tellg()

  // std::ios_base::ate seeks to the end of the file on construction of ifstream
std::ifstream rad ("file.txt", std::ios_base::ate);
int length = 0;
if (rad) {
length = is.tellg();
is.seekg (0, std::ios_base::beg); // reset it to beginning if you want to use it
}
// .. use length

关于c++ - 如何查找输入文件的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35313589/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com