簡體   English   中英

在while循環中使用scanf

[英]Usage of scanf in while loop

我必須使用scanf從文件中讀取一系列輸入。 但是在兩種情況下會有不同的結果。 代碼1-讀取一個整數和一個char數組。

char plaintext[20];
int started = 0;
int x;


while (scanf("%i,%19[^\n]",&x,plaintext) == 2)
{
    if (started == 1)
        printf(",\n");
    else 
            started = 1;
    printf("i read a line from a file");
}
printf("\n");

這工作得很好。 scanf讀取文件中的每一行,而printf()輸出每行輸入所需的行。

代碼 2-僅讀取char數組

char plaintext[20];
int started = 0;

while (scanf("%19[^\n]",plaintext) == 1)
{
    if (started == 1)
        printf(",\n");
    else 
            started = 1;
    printf("i read a line from a file");
}
printf("\n");

在這里,scanf只讀取第一行,並且僅打印一次“我從文件讀取行”。

一種解決方案是在代碼2的scanf中使用%* c。但是為什么代碼1可以正常工作,而代碼2卻不能工作。

你需要改變

scanf("%19[^\n]",plaintext)

以便在讀取第一行后讀取緩沖區中的新行字符。

嘗試

scanf("%19[^\n] ",plaintext)

空格讀取行尾的換行符

暫無
暫無

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

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