Help with scanf behaving differently on Big Endian system
My code is supposed to read a line from the user, if the line starts with "output" then it pri开发者_JAVA百科nts 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);
....
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.
精彩评论