马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
程序清单4.1 talkback.c程序
//talkback.c -- 演示与用户交互
//talkback.c -- 演示与用户交互
/*这是书中的例子*/
#include<stdio.h>
#include<string.h>
#define DENSITY 62.4
int main(void)
{
float weight, volume;
int size, letters;
char name[40]; //name是一个可容纳40个字符的数组
printf("Hi!What's your name?\n");
scanf_s("%s", name);
printf("%s,what's you weight in pounds?\n", name);
scanf_s("%f", &weight);
size = sizeof name;
letters = strlen(name);
volume = weight / DENSITY;
printf("Well,%s,your volume is %2.2f cubic feet.\n",
name, volume);
printf("Also,your first name has %d letters,\n",
letters);
printf("and we have %d bytes to store it.\n", size);
return 0;
}
以下是在百度结果的例子//talkback.c -- 演示与用户交互
#include<stdio.h>
#include<string.h>
#define DENSITY 62.4
int main(void)
{
float weight, volume;
int size, letters;
char name[40] = {0}; //name是一个可容纳40个字符的数组
printf("Hi!What's your name?\n");
scanf_s("%s", name,40);
printf("%s,what's you weight in pounds?\n", name);
scanf_s("%f", &weight);
size = sizeof name;
letters = strlen(name);
volume = weight / DENSITY;
printf("Well,%s,your volume is %2.2f cubic feet.\n",
name, volume);
printf("Also,your first name has %d letters,\n",
letters);
printf("and we have %d bytes to store it.\n", size);
return 0;
}
书中例子运行时在键入自己名字后回车,会出现错误,进入stdio.h源文件中(目前暂时没有能力去分析)
网上例子,分别在name[40]后面添加了终止符,然后在scanf_s函数中的name后面添加40
还请各位大神能解答一下,我用的编译器是vs2019.
这没有什么好解释的,scanf_s 函数就是这样用的,scanf_s 函数对于某些变量,要求提供缓冲区的大小
scanf_s 和 scanf 是完全不一样的两个函数,你在看到 scanf_s 的时候不要联想到 scanf,这两个是完全不同的函数
scanf_s 函数有自己的一套规定,和 scanf 函数是不一样的
|