提供的变量地址而不是它的值

Address of variable supplied instead of its value

我想在 C++ 中测试 fopenfclose 的示例,其中代码读取文件中的整数值,但如果文件为空(没有整数),则检索到的值不是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;
    }
}

输出:

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;
}

上面程序的输出可见here.

修复很简单,不会遗漏 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);