124 lines
2.9 KiB
Markdown
124 lines
2.9 KiB
Markdown
# 字符串的读入与输出
|
||
|
||
## 一、$scanf$函数使用
|
||
|
||
### 1、不带空格的字符串
|
||
```cpp {.line-numbers}
|
||
#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、带空格的字符串
|
||
```cpp {.line-numbers}
|
||
#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、按字符串规定格式读取
|
||
#### 【整数】
|
||
```cpp {.line-numbers}
|
||
#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;
|
||
}
|
||
```
|
||
#### 【浮点数】
|
||
```cpp {.line-numbers}
|
||
#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、读取部分内容
|
||
#### 读取数字
|
||
```cpp {.line-numbers}
|
||
#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;
|
||
}
|
||
```
|
||
#### 读取数字+字符串
|
||
```cpp {.line-numbers}
|
||
#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;
|
||
}
|
||
```
|
||
#### 不要指定内容
|
||
```cpp {.line-numbers}
|
||
#include <cstdio>
|
||
using namespace std;
|
||
int main() {
|
||
char str[32];
|
||
sscanf("123456abcdedf", "%31[^a-z]", str);
|
||
printf("str=%s\n", str);
|
||
return 0;
|
||
}
|
||
```
|
||
|
||
## 三、$sprintf$函数使用
|
||
### 拼接字符串
|
||
```cpp {.line-numbers}
|
||
#include <cstdio>
|
||
using namespace std;
|
||
const double PI = 3.1415926;
|
||
int main() {
|
||
char str[80];
|
||
sprintf(str, "Pi= %lf", PI);
|
||
puts(str);
|
||
return (0);
|
||
}
|
||
```
|
||
|
||
#### 其它常见用法
|
||
```cpp {.line-numbers}
|
||
//把整数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 个位置,左对齐
|
||
``` |