帮助 scanf 在 Big Endian 系统上表现不同
我的代码应该从用户那里读取一行,如果该行以“output”开头,那么它会打印出“Line is output”并等待用户输入另一条线。
如果该行以“input”开头,则会打印出“Line is input”并终止。
我的代码在 Intel PC 上运行良好,但是在 Debian SPARC 上,scanf 似乎在第一次后不会等待输入,而只是无限地读取空行或其他内容。
我这里哪里出错了?
#include <stdio.h>
#include <string.h>
int main()
{
char buf[9000];
char key[5];
char *p=buf;
int readMore=1;
while(readMore)
{
//read in one line from stdin into buffer
scanf("%[^\n]",buf);
fflush(stdin);
sscanf(p, "%s",key); //get key from buffer
printf("Key:%s\n",key); //print key
if (strcmp("output",key)==0)
{
printf("Line is output\n");
}
if (strcmp("input",key)==0)
{
readMore=0;
printf("Line is input\n");
fflush(stdin);
getchar();
return 0;
}
key[0]=0;
buf[0]=0;
} //end while
return 0;
}
固定如下:
......
int bytes_read;
int nbytes = 100;
while(readMore)
{
/* These 2 lines are the heart of the program. */
p = (char *) malloc (nbytes + 1);
bytes_read = getline (&p, &nbytes, stdin);
....
My code is supposed to read a line from the user, if the line starts with "output" then it prints out "Line is output" and waits for the user to enter another line.
If the line starts with "input" it prints out "Line is input" and terminates.
My code works fine on an Intel PC, however on a Debian SPARC it seems the scanf doesnt wait for input after the first time and just reads in an empty line or something infinitely.
Where am I going wrong here?
#include <stdio.h>
#include <string.h>
int main()
{
char buf[9000];
char key[5];
char *p=buf;
int readMore=1;
while(readMore)
{
//read in one line from stdin into buffer
scanf("%[^\n]",buf);
fflush(stdin);
sscanf(p, "%s",key); //get key from buffer
printf("Key:%s\n",key); //print key
if (strcmp("output",key)==0)
{
printf("Line is output\n");
}
if (strcmp("input",key)==0)
{
readMore=0;
printf("Line is input\n");
fflush(stdin);
getchar();
return 0;
}
key[0]=0;
buf[0]=0;
} //end while
return 0;
}
Fixed like this:
......
int bytes_read;
int nbytes = 100;
while(readMore)
{
/* These 2 lines are the heart of the program. */
p = (char *) malloc (nbytes + 1);
bytes_read = getline (&p, &nbytes, stdin);
....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是字节序问题。这是关于如何在不同平台上执行标准输入的缓冲。基本上,您不能在标准输入(或任何其他输入流)上使用 fflush() - C 标准表示这样做是未定义的。
This is not an endian issue. This is about how buffering of standard input is performed on the different platforms. Basically, you can't use fflush() on standard input (or any other input stream) - the C Standard says that doing so is undefined.