[英]Why is my program got into an infinite loop?
我想掃描一行直到按下換行符。 我知道gets()
函數,但是我想用scanf()
學習它。 問題是,我的程序陷入無限循環,在此循環中,它將掃描用戶的輸入,然后將其無限地打印出來,在每次掃描后均應打印一次。 有人可以解釋為什么它會這樣嗎?
#include<stdio.h>
int main()
{
char str[100];
while(str[0]!='\0')
{
scanf("%[^\n]",str);
printf("%s\n",str);
}
}
如果您堅持使用scanf,則更改格式說明符:
" %[^\n]"
前面的空格將跳過之前的任何“懸空” \\ n
另外,您應該在檢查str數組的內容之前對其進行初始化,最好使用do-while-loop
代替。
這樣的事情應該工作
char str[100] = {0};
do
{
scanf(" %[^\n]",str);
printf("%s\n",str);
}
while(str[0]!='q');
就我個人而言,我更喜歡將fgets(...)
與sscanf(...)
結合使用sscanf(...)
檢查scanf的返回值也是一種好習慣,有一個返回值是有目的的。
添加了另一個while條件,循環直到“ q”或“ quit”
由於%[^\\n]
不接受換行符,因此第二個循環中不接受輸入。
可能,這會做您想要的。
#include<stdio.h>
int main(void){
char str[100];
while(1== scanf("%99[^\n]%*c",str)){//%*c consumes newline. Also In case of only newline terminates the loop
printf("%s\n",str);
}
}
BLUEPIXY是絕對正確的。 scanf()
的第一個返回值是將\\n
保留在輸入緩沖區中。 隨后的scanf()
調用將立即返回,而不會從stdin
讀取任何字符,因為scanf()
停止在\\n
上讀取。 這樣便出現了循環。 避免循環的一種方法是在調用scanf()
之后從輸入中讀取\\n
,如下所示:
#include <stdio.h>
int main()
{
char str[100] = {0};
do
{
scanf("%[^\n]",str);
getchar();
printf("%s\n",str);
}while( str[0] != '\0' );
}
您似乎對輸入的工作方式有一些錯誤的信念。 所以我將在下面解釋。
您不需要循環執行此操作,因為在指定字符串格式時, scanf()
不會一次讀取並返回一個字符。 輸入由終端buffered
。 當您要求scanf()
返回字符串時,終端只會在收到newline
時才將輸入字符串發送到scanf()
。 發生這種情況時, scanf()
返回不包含newline
的字符串。
您需要做一些額外的工作來關閉終端線緩沖。 下面的示例代碼顯示了如何關閉終端I / O緩沖。
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
int main()
{
struct termios old_tio, new_tio;
unsigned char c;
/* get the terminal settings for stdin */
tcgetattr(STDIN_FILENO,&old_tio);
/* we want to keep the old setting to restore them a the end */
new_tio=old_tio;
/* disable canonical mode (buffered i/o) and local echo */
new_tio.c_lflag &=(~ICANON & ~ECHO);
/* set the new settings immediately */
tcsetattr(STDIN_FILENO,TCSANOW,&new_tio);
do {
c=getchar();
printf("%c ",(char)c);
} while(c!='q');
/* restore the former settings */
tcsetattr(STDIN_FILENO,TCSANOW,&old_tio);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.