【标准io】printf(fprintf、sprintf)函数和scanf函数

橙色

printf和scanf

printf——族函数

  • printf:发送格式化输出到标准输出 stdout。

ps:stdin默认是通过键盘输入,而stderr和stdout是默认输出到终端。也可以通过重定向改变。比如编译程序时可能会出现警告或者一些输出内容,我们就可以把输出重定向到一个文件中,把标准出错stderr重定向到某一个文件当中

int printf(const char *format, ...);
  • fprintf:发送格式化输出到流 stream 中。可以实现格式化输出的重定向,例如重定向至文件中。
int fprintf(FILE *stream, const char *format, ...);
  • sprintf:发送格式化输出到 str 所指向的字符串。它能够将多种数据类型(整型、字符型)的数据综合为字符串类型。有溢出风险,可以使用snprintf来防止。
int sprintf(char *str, const char *format, ...)
  • atoi:把参数 str 所指向的字符串转换为一个整数(类型为 int 型)。包含在stdlib.h中。
int atoi(const char *str)

代码示例:
展示atoi的作用

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char str[] = "123456";

    printf("%d\n", atoi(str)); // 123456

    exit(0);
}

atoi遇到字符就会停止

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char str[] = "123a456";
	// 遇到字符就停止
    printf("%d\n", atoi(str)); // 123

    exit(0);
}

将格式化输出重定向为字符串

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char buf[1024];
    int year = 2022, month = 11, day = 28;
	
    // 将格式化输出重定向为字符串
    sprintf(buf, "%d-%d-%d", year, month, day);
    puts(buf);

    exit(0);
}
  • 16
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

努力学习的小马

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

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

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

打赏作者

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

抵扣说明:

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

余额充值