字符串和格式化输入/输出(1)

本篇摘要:

1:章节导入 

2:字符串和字符

---------------------------------------------------------------------------------------------------------------------------------

分析两者的区别: 

# include <stdio.h>
# include <string.h>
# define DENSITY 62.4
int  main()
{
	float weight, volume;
	int size, letters;
	char name[40];
	
	printf("Hi what's your first name?\n");
	scanf_s("%s", name);
	printf("%s,What's 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;


}
#include <stdio.h>
#include <string.h>

#define DENSITY 62.4

int main(void) {
	float weight, volume;
	int size, letters;
	char name[40];

	printf("Hi, what's your first name?\n");
	scanf_s("%s", name, sizeof(name));  // 增加了缓冲区大小参数
	printf("%s, what's your 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;
}

如果使用 scanf_s 函数,则还需要提供字符串缓冲区的大小:

此处两个%s,因为程序要打印两次,一个存储在name中,一个由PRAISE来存储。

字符串和字符:

字符和字符串的主要区别

  1. 存储方式

    • 字符:占用一个字节(char 类型)。
    • 字符串:占用多个字节,是字符数组,以空字符 \0 结尾。
  2. 表示方式

    • 字符:用单引号,例如 'A'
    • 字符串:用双引号,例如 "Hello"
  3. 操作方式

    • 字符:可以直接进行比较、赋值等简单操作。
    • 字符串:通常需要使用库函数进行操作,如 strlenstrcpystrcmp 等。

常见字符串操作函数

  1. strlen:计算字符串长度,不包括末尾的空字符。

  2. #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str[] = "Hello, World!";
        int length = strlen(str);
        printf("Length of string: %d\n", length);
        return 0;
    }

    strcpy:复制字符串。

  3. #include <stdio.h>
    #include <string.h>
    
    int main() {
        char src[] = "Hello, World!";
        char dest[50];
        strcpy(dest, src);
        printf("Copied string: %s\n", dest);
        return 0;
    }

    strcat:连接两个字符串。

  4. #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str1[50] = "Hello, ";
        char str2[] = "World!";
        strcat(str1, str2);
        printf("Concatenated string: %s\n", str1);
        return 0;
    }

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值