2013-01-24 132 views
2

編寫一個類的程序,僅限於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. 

我希望我的輸出是相同的,以我的輸入。使用scanf。

+0

[使用scanf()讀取多行輸入的可能的重複)(http://stackoverflow.com/questions/13592875/reading-multiple-lines-of-input-with-scanf) – user2284570

回答

3

試試這個代碼,並使用Tab鍵作爲分隔符

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

    return 0; 
} 
+0

我曾嘗試過。拋出「中止陷阱:6」。 – John

+0

你能告訴我什麼是你使用的價值作爲輸入 –

+0

我認爲這是因爲內存問題,因爲C不是一種內存安全的語言。 –

1

我給你一個提示。

您需要重複scanf操作,直到達到「EOF」條件。

,通常列做的方式是與

while (!feof(stdin)) { 
} 

結構。

+1

-1:''而(!feof(..))'幾乎總是錯誤的,並且總是得到最後一行錯誤,除非你進行英雄式的後期處理。 –

7

我想你想要的是像這樣(如果你真的只限於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(). 

[編輯:刪除誤導性的答案,每多德的撲:)]

+0

+1爲正確的第一個答案,-1爲完全錯誤且誤導性的第二個答案。爲什麼人們不斷推薦'while(!feof)'?一個肯定的消息指示程序員不知道他們在做什麼。 –

+0

如何消除最後一行輸出中的額外換行符(\ n)? – John

+0

否則它太棒了,謝謝! – John

0

嘗試這一塊的代碼.. 它可以按照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; 
}