stringstream sscanf sprintf
2020-02-22 17:21:31
本文总阅读量

stringstream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <sstream>

using namespace std;

// 从一行输入中扣数字
int main()
{
int a[10];

string line;
getline(cin, line); // 12 32 4 44 56 88888 4

stringstream ssin(line);

int cnt = 0;
while (ssin >> a[cnt++])
;

for (int i = 0; i < cnt - 1; i++)
printf("%d ", a[i]);

return 0;
}

sscanf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <string>

using namespace std;

// 从特定的序列中扣数
// 例如 23:16:36
int main()
{
string line;
getline(cin, line);

int h, m, s;
sscanf(line.c_str(), "%d:%d:%d", &h, &m, &s);

printf("%d %d %d", h, m, s);

return 0;
}

sprintf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <string>

using namespace std;

// 按照固定格式转化为字符串
int main()
{
//string str; 不知道为啥 str.c_str() 不能用

char str[128];

int h = 23, m = 1, s = 26;

sprintf(str, "%02d:%02d:%02d", h, m, s);

cout << str << endl;

return 0;
}