简体   繁体   中英

scanning strings and ints from stdio in C

I am trying to read two ints and a string input from stdio in this format:

22 CHEESE 2

into two different int variables and a string variable, as seen below.

        int newId, newQuantity;
        char newName[20];
        scanf("%d %s %d",&newId, newName, &newQuantity);

The code properly reads the string, but immediately after the inputs are entered, when I test to see what the value of newId and newQuantity are, they are always these large ints that are never what I input. I check for the change in inputs by modifying my code to show the following:

        int newId, newQuantity;
        char newName[20];
        scanf("%d %s %d",&newId, newName, &newQuantity);
        printf("%d %s %d",&newId, newName, &newQuantity);

and when I input 22 CHEESE 2, for instance, it prints -1957382872 CHEESE -1957382868. I was wondering if there was any way of rectifying this? Any help is appreciated.

This printf("%d %s %d",&newId, newName, &newQuantity) is wrong and should be printf("%d %s %d",newId, newName, newQuantity) , and is something you would have discovered if you enabled compiler warnings .

Here is the warnings:

$ gcc main.c -Wall -Wextra
main.c: In function ‘main’:
main.c:7:18: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
         printf("%d %s %d",&newId, newName, &newQuantity);
                 ~^        ~~~~~~
                 %ls
main.c:7:24: warning: format ‘%d’ expects argument of type ‘int’, but argument 4 has type ‘int *’ [-Wformat=]
         printf("%d %s %d",&newId, newName, &newQuantity);
                       ~^                   ~~~~~~~~~~~~
                       %ls

This question is a PERFECT example of why you always should provide a mcve when you ask a question. The problem was not where you thought it was, but instead in code you did not show us at first. It is also a perfect example of why you should have compiler warnings enabled and read them. They often provide very good clues. A warning is the compilers way of saying "This code is valid, but it probably does not do what you want."

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