繁体   English   中英

无法读取C中的输入线

[英]Cant read input line in 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(stdin,...)用fgets(stdin)代替scanf(),获取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)进行编译。

谁能看到我在做什么错?

在scanf中,您应该使用%i表示一个int,因此,尝试使用

 scanf("%I", number_line);

以下代码将起作用,

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
    }

}

您可以根据自己的情况打破循环

尝试read()在MinGW中工作替换

这个

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

#include<unistd.h>还包括#include<unistd.h>

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

scanf返回的值不是要读取的元素数中的字符串数(本例为meybe 1)。

使用%n获取所需的数字。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM