You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2.9 KiB

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

字符串的读入与输出

一、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 个位置,左对齐