C语言基础入门48篇_07-scanf的基本使用(利用&进行普通变量及数组地址获取)

本文详细介绍了C语言中scanf函数的基础使用方法,包括如何通过格式化字符串读取不同类型的输入数据,如整数、字符、小数和字符串,并强调了正确的格式匹配与地址操作的重要性。

1. scanf格式化输入基本使用
scanf的第一个参数为格式化字符串,与printf类似,有“%”开头的格式控制符,每一个格式控制符对应后续一个参数。
scanf函数从标准输入(键盘)中读取数据至后续参数所指定的位置,因此,后续的每一个参数都应该指向一个内存地址。

#include <stdio.h>

int main(int argc, char* argv[])
{
 int nValue = 0;
 scanf("%d", &nValue);
 printf("Your input is %d\r\n", nValue);
 return 0;
}

2. C语言中如何获取变量的地址
C语言程序中的每一个变量,在程序运行时,都会被分配内存空间,CPU依靠内存地址(类似门牌号码)找到对应的变量。

  • 对于普通的变量,我们可以通过C语言中的取地址符&获取变量的地址
  • 对于数组变量,数组的名字就是数组的首地址
int nValue = 0;
printf("%08X", nValue);
printf("%08X", &nValue);

int nValueAry[5] = {0};
printf("%08X", nValueAry);

3. 利用scanf进行数据输入
第一个参数是格式化字符串,scanf根据格式化字符串指定的类型,将键盘输入的内容存储到后续参数中指定的位置中去。
(1)输入一个整数并输出:

#include <stdio.h>

int main(int argc, char* argv[])
{
 int nValue = 0;
 scanf("%d", &nValue);
 printf("Your input is: %d\r\n", nValue);
	
 return 0;
}

(2)输入一个字符并输出

#include <stdio.h>

int main(int argc, char* argv[])
{
 char chValue = 0;
 scanf("%c", &chValue);
 printf("Your input is: %c\r\n", chValue);
	
 return 0;
}

(3)输入一个小数并输出

#include <stdio.h>

int main(int argc, char* argv[])
{
 double dbValue = 0;
 scanf("%lf", &dbValue);
 printf("Your input is: %lf\r\n", dbValue);
	
 return 0;
}

(4)输入一个字符串并输出

#include <stdio.h>

int main(int argc, char* argv[])
{
 char szBuff[20] = { 0 };
 scanf("%s", szBuff);
 printf("Your input is: %s\r\n", szBuff);
	
 return 0;
}

4. scanf的进一步细节
为什么scanf是“格式化输入”
(1)比较以下情形:键盘输入一样,但是分别采用%d与%X来输入数据。

#include <stdio.h>

int main(int argc, char* argv[])
{
 int nValue = 0;
 scanf("%d", &nValue);
 printf("Your input is: %d\r\n", nValue);
	
 return 0;
}
#include <stdio.h>

int main(int argc, char* argv[])
{
 int nValue = 0;
 scanf("%x", &nValue);
 printf("Your input is: %d\r\n", nValue);
	
 return 0;
}

(2)其次,键盘的输入应该与格式化字符串的格式完全一致:

#include <stdio.h>

int main(int argc, char* argv[])
{
 int nValue1 = 0;
 int nValue2 = 0;
 scanf("%d,%d", &nValue1, &nValue2);
 printf("Your input is: %d, %d", nValue1, nValue2);
	
 return 0;
}

5. 对于初学者建议:

  • 不要一次性读取多个变量
  • 对于字符串的读取,记得限制长度
#include <stdio.h>

int main(int argc, char* argv[])
{
 char szBuff[20] = { 0 };
 scanf("%19s", szBuff);
 printf("Input is: %s", szBuff);
	
 return 0;
}

6.学习视频地址:scanf的基本使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十月旧城

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值