簡體   English   中英

您可以使用“fscanf”讀取單個字符和整數嗎?

[英]Can you use 'fscanf' to read in individual chars and an int?

我正在嘗試轉換一些代碼,這些代碼每行 txt 文件讀取三個整數,直到文件結束。 IE:

int int int
int int int
int int int

我現在要做的是讀入:

z z 5
z z 6
z z 5

直到文件結束。

打開文件后我遇到了問題。 我放置了幾個調試器來跟蹤進度並評論了打印的內容。 它只顯示文件第一行的前后。 所以我猜它只是讀一行。

        int i,origin,destin,wt;
        char a, b;
        int nodes = 0;
        
        printf("before file is opened\n"); // displayed

        FILE *fptr = fopen("input.txt","r");

        printf("after file is opened\n"); // displayed

        while (fscanf(fptr, "%c %c %d", &a, &b, &wt) == 3){
            
            printf("\before is : %c %c\n", a, b);  // shows the first line of file   
            origin = convertToNum(a);
            destin = convertToNum(b);
            
            printf("\nconversion is : %d %d\n", origin, destin); // 1st line of file shown
        }

編輯更改:

while (fscanf(fptr, "%c %c %d", &a, &b, &wt) == 3)

至:

while (fscanf(fptr, "%c %c %d", &a, &b, &wt) != EOF)

產生稍微好一點的結果。 它會在一行中讀取就好了。 每隔一行似乎都有空格問題。

我沒有意識到 %c 也抓住了換行符。

char buf[512];
    while (fgets(buf, sizeof buf, fptr) != 0) {
        sscanf(buf, "%c %c %d", &a, &b, &wt);

暫無
暫無

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

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