简体   繁体   中英

C - printf() not working correctly?

I'm writing a simple program which takes data about people in this format: name,age,gender,info

and it will display them like this [name: , age: , gender: , info: ]

Here is my code so far:

#include <stdio.h>

int main() {
char name[10];
int age;
char gender[2];
char info[50];

while(scanf("%9[^,],%i,%c,%49[^\n]", name, &age, gender, info) == 4) {
    printf("[name: %s, age: %i, gender: %c, info: %s]\n", name, age, gender, info);
}

return 0;

}

So I decided to write my output to another text file using >. And it does nto display correctly, the ] bracket displays on a new line and [name: by itself.

This is my input:

 eliza,7,F,likes animals
 bob,9,M,fast at running
 sue,6,F,likes painting

And the output is:

 [name: eliza, age: 7, gender: J, info: likes animals
 ]
 [name: 
 bob, age: 9, gender: J, info: fast at running
 ]
 [name: 
 sue, age: 6, gender: J, info: likes painting
 ]

Can someone help? I can't figure out why it prints the data like this, I tried using strstr() to check if any of my variables contained the new line character.

You have two issues. Firstly, I believe this is windows (or at least the file you're reading was created in Windows), which means you have \\r\\n not just \\n at line endings. You can fix that by opening the file in text mode but that's unreliable; it's better to filter the extra \\r out manually.

That's what puts a newline after each "info" field.

The second problem is that you reject the \\n from the info field, so it's still there as the first character for later "name" fields, which is why you have the extra line break there. To fix it, just put a space at the start of your scanf string (which will swallow any and all whitespace)

And Inspired points out your third issue (which I hadn't noticed); you need to treat gender as a character not a string. The "correct" way to read it is like this:

char gender; // no need to have an array of characters
scanf( "blah %c blah", &gender );

and print like:

printf( "blah %c blah", gender );
#include <stdio.h>

int main(void) {
    char name[10];
    int age;
    char gender;//change
    char info[50];

    while(scanf("%9[^,],%i,%c,%49[^\n]%*c", name, &age, &gender, info) == 4) {
        printf("[name: %s, age: %i, gender: %c, info: %s]\n", name, age, gender, info);
    }

    return 0;
}

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