字符串的读入与输出

一、scanf函数使用

1、不带空格的字符串

#include<cstring>
#include<cstdio>
using namespace std;
int main(){
    char a[110];
    scanf("%s",a);
    printf("%d\n",strlen(a));
    for(int i=0;i<strlen(a);i++)
        printf("%c",a[i]);
    return 0;
}

2、带空格的字符串

#include<cstring>
#include<cstdio>
using namespace std;
int main(){
    char a[110];
    scanf("%[^\n]%*c",a); //利用正则表达式一直读取到\n为止,并且清除最后一个缓冲
    printf("%d",strlen(a));
    return 0;
}

二、sscanf函数使用

1、按字符串规定格式读取

【整数】

#include <cstdio>
using namespace std;
int main() {
    int year, month, day;
    int cnt = sscanf("20191103", "%04d%02d%02d", &year, &month, &day);
    printf("cnt=%d, year=%d, month=%d, day=%d\n", cnt, year, month, day);
    return 0;
}

【浮点数】

#include <cstdio>
using namespace std;
int main() {
    double longitude, latitude;
    int cnt = sscanf("113.123456789 31.123456789", "%lf %lf", &longitude, &latitude);
    printf("cnt=%d, longitude=%.9lf, latitude=%.2lf\n", cnt, longitude, latitude);
    return 0;
}

2、读取部分内容

读取数字

#include <cstdio>
using namespace std;
int main() {
    char str[32] = "";
    // 31表示共32个字符,最后一位留给\0
    sscanf("123456abcdedf", "%31[0-9]", str);
    printf("str=%s\n", str); //输出123456
    return 0;
}

读取数字+字符串

#include <cstdio>
using namespace std;
int main() {
    char str[32] = "";
    int ret = sscanf("123456abcdedf", "%31[0-9a-z]", str);
    printf("res=%d str=%s\n", ret, str);
    return 0;
}

不要指定内容

#include <cstdio>
using namespace std;
int main() {
    char str[32];
    sscanf("123456abcdedf", "%31[^a-z]", str);
    printf("str=%s\n", str);
    return 0;
}

三、sprintf函数使用

拼接字符串

#include <cstdio>
using namespace std;
const double PI = 3.1415926;
int main() {
    char str[80];
    sprintf(str, "Pi= %lf", PI);
    puts(str);
    return (0);
}

其它常见用法

//把整数123 打印成一个字符串保存在s 中。
sprintf(s, "%d", 123); //产生"123"

//可以指定宽度,不足的左边补空格:
sprintf(s, "%8d%8d", 123, 4567); //产生:" 123 4567"

//当然也可以左对齐:
sprintf(s, "%-8d%8d", 123, 4567); //产生:"123 4567"

//也可以按照16 进制打印:
sprintf(s, "%8x", 4567); //小写16 进制,宽度占8 个位置,右对齐

sprintf(s, "%-8X", 4568); //大写16 进制,宽度占8 个位置,左对齐
posted @   糖豆爸爸  阅读(205)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
历史上的今天:
2014-12-04 前端代码优化的基本原则
Live2D
点击右上角即可分享
微信分享提示