简体   繁体   中英

C - Using scanf on a string to get in a number

I will try to be very short on what my problem is. Although, I am a beginner programmer, so I am really sorry for my foolish question.

I have a character string. I want to use scanf to give this string a value. This value can even be a single number (but I want that number as a character as well).

So I did this code:

char string[20];
scanf("%s", string);

//LETS ASSUME WE ONLY WRITE THE NUMBER 1 IN THE STRING

if(string=='1')
 printf("You have entered a single number: 1");

// IF I WOULD RUN THIS PROGRAM THE PRINTF PART WOULD NOT HAPPEN. WHY?

This code is just an example of course. In my program I would do a different thing with IF than a simple printf.

Although, with this code, if I give the string 1 as the value and then press enter, the thing I wrote in IF would not happen for some reason.

Can anyone give me an explanation on how should I do this then to make it work? How should I write the IF part then?

Use (be careful as single quotes mean a char value and not a string literal)

#include <string.h>

...

if (strcmp(string, "1") == 0) /* if it returns 0, the string contents are the same for both strings */

...

as C doesn't have direct support to do string comparison, and you are actually comparing two pointers (even if they have the same value stored, it will not be the same pointer as the string literal "1" and the string variable are located in different places in your computer memory.

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