简体   繁体   中英

C Linux printf mangled result

I am having some issues whenever the user inputs a pipe "|" character the output becomes all mangled, I have already tried flushing the buffer to no avail.

#include <stdio.h>

int main(int argc, char **argv)
{
    char userInput[2000];
    while(1)
    {
        printf("Please Enter Your Input:");
        scanf("%s", userInput);
        printf("%s\n", userInput);
    }
    return 0;
}

There are a couple of things you can do to debug this. First - read in the entire input line, rather than the first word. The safe way to do this is with getline() - it will notice if the line is too long for your input buffer, and adjust things (updated with thanks to Elchonon Edelson)

char *myString;
int stringLength;
size_t bufLength=0;
myString = NULL; // let getline() adjust the string
stringLength = getline(&myString, &bufLength, stdin)

Next, print out the line as entered:

printf("The line is <<%s>>\n", myString);

Note the use of << and >> to show where the string starts / ends - see white space etc.

Finally, print out the string one character at a time, including the hex code:

for(ii = 0; ii < stringLength; ii++) {
  char ch;
  ch = myString[ii];
  printf("myString[%d]: character '%c', hex code %02x\n", ii, ch, ch);
}

This should help you pinpoint the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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