i灣測驗的一個例子fopen和fclose在C 其中代碼讀取整數值在你的檔案,但如果該檔案是空的(沒有整數),檢索到的值不是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
uj5u.com熱心網友回復:
執行此操作的更多 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;
}
上面程式的輸出可以在這里看到。
uj5u.com熱心網友回復:
修復很簡單,永遠不會錯過 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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/400187.html
標籤:C 视觉工作室-2010
