簡體   English   中英

fscanf返回錯誤的數字

[英]fscanf returns wrong numbers

我正在嘗試讀取一個看起來像這樣的文本文件

8
6 1 2.2
1 2 1.0
4 3
1 3
4 5 1.2
2 4 0.0
5 2
6 6
3 4

這是我的代碼

int nodes;
FILE* file = fopen(argv[1], "r");
fscanf(file, "%d",  &nodes);
printf("n = %d\n", nodes);

while (1) {

    int node = 0, link = 0;
    float weight = 0.0;

    if (fscanf(file, "%d %d %f \n", &node, &link, &weight) < 1) {
        break;
    } else {
        printf("%d %d %.1f \n", node, link, weight);
    }
}

這是輸出

n = 8

6 1 2.2
1 2 1.0
4 3 1.0 
3 4 5.0 
1 0 0.0

如果以其他方式設置輸入格式,則會發現該錯誤很容易

8
6 1 2.2
1 2 1.0
4 3 1
3 4 5
1.2 2 4
0.0 5 2
6 6 3
4

fscanf嘗試通過轉換"%d"讀取1.2 ,它會將1分配給相應的變量,並將點保留在緩沖區中以備下次讀取。

下一次讀取再次使用轉換"%d" ,該轉換不接受點作為有效輸入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM