第四章(4.1;4.2) 字符串和格式化输入输出

1.scanf中用%s转换说明来处理字符串的输入和输出

2.sizeof运算符,它以字节为单位给出对象的大小。strlen()函数给出字符串中的字符长度

3.处理以下错误方法

警告    1    warning C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.    d:\vs2010\ybqprojects\4.2.3\4.2.3\praise2.c    11    1    4.2.3

在头文件包含的最前面,记住是最前面(在include的前面)加上:#define _CRT_SECURE_NO_WARNINGS这个宏定义即可,更多方法详见收藏

4.1  演示与用户交互

//talkback.c
#include<stdio.h>
#include<string.h>  //提供strlen()函数的原型
#define DENSITY 62.4  //人体密度(单位:磅/立方英尺)
int main()
{
    float weight,volume;
    int size,letters;
    char name[40];  //name是一个可容纳40个字符的数组

    printf("hi!what's your first name?\n");
    scanf("%s",name);  //(用%s转换说明来处理字符串的输入和输出)
    printf("%s,what's your weight in pounds?\n",name);
    scanf("%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);

    getchar();
    getchar();
    return 0;
}

输出:hi!what's your first name?
           Daniel
           Daniel,what's your weight in pounds?
          172
          well,Daniel,your volume is 2.76 cubic feet,
          also,your first name has 6 letters,
          and we have 40 bytes to store it.

4.2//使用不同类型的字符串
#include<stdio.h>
#define PRAISE "you are an extraordinary being."
int main(void)
{
    char name[40];  //name是一个可容纳40个字符串的数组

    printf("what's your name?");
    scanf("%s",name);
    printf("Hello,%s.%s\n", name,PRAISE);

    
    getchar();
    getchar();
    return 0;
}

输出:what's your name?
           Daniel
           Hello,Daniel.you are an extraordinary being.

发布了10 篇原创文章 · 获赞 0 · 访问量 2381

猜你喜欢

转载自blog.csdn.net/YBQ9558/article/details/88901725