2014-02-07 53 views
0

对不起,一个愚蠢的问题,但这真的开始困扰着我。不能读取输入行C

我需要从控制台取一行输入。这是相关的代码片段:

int number_read=0; 
char line[80]; 

printf("Enter register address: "); 
number_read = scanf("%s\n", line); 
printf("number of characters entered: %d; characters entered: %s.\n", number_read, line); 
if (number_read > 0) { 
    <read some registers and display the results.> 
} 

它不起作用。打印“输入寄存器地址”行,光标停在行的末尾,当我按下Enter时移动到下一行,但是没有其他事情发生。我试着更换的fscanf scanf()的(标准输入,...),用于fgets(标准输入),获取,GNU的函数getline(),很短的函数,做同样的事情,与诊断:

char *new_line, ch; 
for(;;) { 
    ch = fgetc(stdin); 
    if(ch == EOF) break; 
    if((*line++ = ch) == '\n') break; 
    printf("Line so far: %s\n", line); 
} 
*line='\0'; 

我得到了所有人的同样答复。我包含了所有必需的标题。

我在一个Windows XP的盒子上,用gcc 3.4.5(mingw)编译。

任何人都可以看到我做错了什么?

+0

remove从scanf函数,将工作 – user2760375

+1

可编译的例子可能是有帮助的“\ n”,有机会,这个问题是不是你认为它是。 –

+0

感谢user2760375,但它没有区别。 – user3282703

回答

0

在scanf函数,你应该使用%i来代表一个INT因此,与

scanf("%I", number_line); 
+0

谢谢安东尼奥,但我希望输入是一个char *(实际上是一个字符数组),而不是一个int。 – user3282703

+0

呃确定抱歉误会您的问题。 –

+0

number_read = read(STDIN_FILENO,(void *)line,sizeof line);它将工作,但只在linux – user2760375

0

尝试下面的代码将作品,

char buff_msg[1024]; 
while(1) 
{ 
    if(fgets(buff_msg,1024, stdin) != NULL){ 
     printf("%s\n", buff_msg); 

     memset(buff_msg, 0, 1024); // you will need this line 
    } 

} 

可以 打破自己的条件循环

0

尝试读取()它在MinGW中取代

number_read = scanf("%s\n", line); 

与此也包括#include<unistd.h>

number_read = read(STDIN_FILENO, (void *)line,sizeof line); 
0

值scanf的返回不在元件读取的数串的数目(在此情况下meybe 1)。

使用%n获取数字,如所需。

scanf("%s%n", line, &number_read); 
printf("number of characters entered: %d; characters entered: %s.\n", number_read, line);