简体   繁体   English

C - 在字符串上使用scanf来获取数字

[英]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. 我想使用scanf为这个字符串赋值。 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. 在我的程序中,我会用IF做一个不同于简单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. 虽然,使用此代码,如果我将字符串1作为值,然后按回车键,我在IF中写的东西不会因某种原因发生。

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? 那我该怎么写IF部分呢?

Use (be careful as single quotes mean a char value and not a string literal) 使用(小心单引号表示char值而不是字符串文字)

#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. 因为C没有直接支持进行字符串比较,而你实际上是在比较两个指针(即使它们存储了相同的值,它也不会是与字符串文字"1"相同的指针,并且string变量位于在你的计算机内存的不同地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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