簡體   English   中英

使用scanf讀取多行輸入

[英]Reading multiple lines of input with scanf

為類編寫程序,僅限於scanf方法。 程序接收可以接收任意數量的行作為輸入。 使用scanf接收多行輸入時出現問題。

#include <stdio.h>
int main(){
    char s[100];
    while(scanf("%[^\n]",s)==1){
        printf("%s",s);
    }
    return 0;
}

輸入示例:

Here is a line.
Here is another line.

這是當前的輸出:

Here is a line.

我希望我的輸出與我的輸入相同。 使用scanf。

我想你想要的是這樣的(如果你真的只限於scanf):

#include <stdio.h>
int main(){
    char s[100];
    while(scanf("%[^\n]%*c",s)==1){
        printf("%s\n",s);
    }
    return 0;
}

%* c基本上會抑制輸入的最后一個字符。

來自man scanf

An optional '*' assignment-suppression character: 
scanf() reads input as directed by the conversion specification, 
but discards the input.  No corresponding pointer argument is 
required, and this specification is not included in the count of  
successful assignments returned by scanf().

[編輯:根據克里斯多德的抨擊刪除誤導性答案:)]

嘗試此代碼並使用Tab鍵作為分隔符

#include <stdio.h>
int main(){
    char s[100];
    scanf("%[^\t]",s);
    printf("%s",s);

    return 0;
}

我會給你一個提示。

您需要重復scanf操作,直到達到“EOF”條件。

通常采用的方式是

while (!feof(stdin)) {
}

構造。

試試這段代碼..它可以在帶有C99標准的GCC編譯器上運行。

#include<stdio.h>
int main()
{
int s[100];
printf("Enter multiple line strings\n");
scanf("%[^\r]s",s);
printf("Enterd String is\n");
printf("%s\n",s);
return 0;
}

暫無
暫無

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

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