[英]Address of variable supplied instead of its value
我想在 C++ 中测试fopen
和fclose
的示例,其中代码读取文件中的 integer 值,但如果文件为空(无整数),则检索到的值不是 0 而是-858993460
。 我认为这是fscanf()
中变量的地址,但我怎么能得到null
或/0
值以下代码有问题
#include <stdio.h>
int main()
{
{
int a, sum = 0 ,num, n = 0;
FILE* pFile;
pFile = fopen("input.txt", "r");
fscanf(pFile, "%d", &num);
while (n != 5) {
n = n + 1;
sum = sum + num;
fscanf(pFile, "%d", &num);
}
fclose(pFile);
printf("I have read: %d numbers and sum is %d \n", n, sum);
scanf("Hi %d", &a);
return 0;
}
}
input.txt:(空)或:
12 32 43 56 78
注意:代码是有问题的,因为num
永远不会被读取为0
,因此循环会继续进行。
我将添加有关该问题的更多详细信息:如果输入文件包含五个整数:
12 32 43 56 78
代码如下:
#include <stdio.h>
int main()
{
{
char str[80];
int a, sum = 0 ,num, n = 0;
FILE* pFile;
pFile = fopen("input.txt", "r");
fscanf(pFile, "%d", &num);
while (n != 5) {
n = n + 1;
sum = sum + num;
fscanf(pFile, "%d", &num);
}
fclose(pFile);
printf("I have read: %d numbers and sum is %d \n", n, sum);
scanf("Hi %d", &a);
return 0;
}
}
output:
I have read: 5 numbers and sum is 221
执行此操作的更多 C++ 方法如下所示。 您可以将此作为参考。
#include <iostream>
#include <fstream>
#include <sstream>
int main()
{
std::ifstream inputFile("input.txt");
std::string line;
int num = 0, sum = 0; //always initialize built in types in local/block scope
if(inputFile)
{
//go line by line
while(std::getline(inputFile, line))
{
std::istringstream ss(line);
//go through individual numbers
while(ss >> num)
{
sum += num;
}
}
}
else
{
std::cout<<"Input file cannot be read"<<std::endl;
}
inputFile.close();
std::cout << "The sum of all the intergers from the file is: "<<sum<<std::endl;
return 0;
}
以上程序的output可以看这里。
修复很简单,永远不会错过 IO 函数的返回值。
FILE* pFile;
// pFile = fopen("input.txt", "r");
// fscanf(pFile, "%d", &num);
// while (n != 5) {
if ((pFile = fopen("input.txt", "r")) == NULL) // If unable to open file
return 1;
while (n != 5 && fscanf(pFile, "%d", &num) == 1) { // And if num is successfully assigned
n = n + 1;
sum = sum + num;
// Odd: fscanf(pFile, "%d", &num);
}
fclose(pFile);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.