[英]C: Reading int values from a file only results in first line of the file being read
我正在 C 中編寫一個 function,它從給定文件中讀取 int 值,並在每次找到指定數字時加 1。 正在讀取的 My.txt 文件在每一行都有一個 int 后跟一個 float。 但是,我的問題是它只讀取第一行數字然后中斷循環。 導致問題的代碼部分是這樣的:
int tally(char fname[], int item) {
int totalSales = 0;
FILE *input;
int intPlaceholder;
FILE *write;
input = fopen(fname, "r");
if (input != NULL) {
for (int i = 0; fscanf(input, "%d", &intPlaceholder) == 1; i++) {
if (intPlaceholder == item) {
totalSales++;
// Adds 1 to total sales after finding a matching item code in the file
printf("Has found a match!");
}
else {
// Does nothing as it hasn't found a matching code
}
printf("\nLooped once.");
}
printf("\nStopped looping.\n");
}
else {
printf("This option is not valid.\n");
return 0; // Could not open the file
}
fclose(input);
return totalSales;
}
我的 current.txt 文件如下所示:
0 87.99
1 3.99
2 7.99
3 10.00
4 8.00
但是我上面的代碼只是通過循環兩次找到 0 和 87(它也不應該找到 87,但這不是我的主要優先事項),而我希望它循環 10 次。
我有一個單獨的 function,它用浮點值而不是 int 做同樣的事情,它工作正常,我真的很困惑為什么這只發生在 int 值上。 為什么這樣做? 我缺少更好的解決方法嗎?
正如我在評論中指出的那樣,您希望fscanf()
“加載”integer 和浮點值,但只分配 integer(在此版本中)。
我在文件名“test.txt”中設置了自己的測試數據:
3 42.42
3 45.58
7 47.47
1 78.23
這是代碼(沒有很多廢話。)
#include <stdio.h>
int tally( char fname[], int item ) {
int totalSales = 0;
FILE *fp = fopen(fname, "r");
if( fp == NULL) {
printf("This option is not valid.\n");
return 0; // Could not open the file
}
int val;
while( fscanf( fp, "%d %*f", &val ) == 1 )
totalSales += val == item;
fclose( fp );
return totalSales;
}
int main( void ) {
printf( "Test %d\n", tally( "test.txt", 3 ) );
printf( "Test %d\n", tally( "test.txt", 7 ) );
printf( "Test %d\n", tally( "test.txt", 4 ) );
return 0;
}
並且,這是結果:
Test 2
Test 1
Test 0
在fscanf()
的格式說明符中使用'*'
,浮點值被“加載”但未分配給任何變量。 現在應該很明顯如何在不考慮同一行上的 integer 的情況下對浮點數求和。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.