getline+ stringstream
例题:错误票据
用getline,stringstream将多行数据读入一个数组中
#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;
const int N = 10010;
int n, res1, res2;
int a[N];
int main()
{
int cnt;
cin >> cnt;
string line; //声明一个字符串变量 line,用于存储从输入流中读取的每一行数据。
//使用 cin >> cnt; 读取一个整数后,输入流中仍然留有一个换行符,这会导致第一个 getline() 读取一个空行。
//所以这里调用了 getline() 来清除输入流中的换行符。
getline(cin, line);
//循环开始,处理每一行数据。
while (cnt--)
{
//从标准输入流 cin 中读取一行数据,将其存储到 line 变量中。
//getline()会一直读取,直到遇到换行符'\n'为止,然后将换行符丢弃,因此 line 中不包含换行符。
getline(cin, line);
//stringstream创建了一个字符串流ssin,它将line中的内容作为自己的输入。
//字符串流实际上就是一个内存中的缓冲区,你可以将其想象成一个临时的输入流,但它的数据来源是一个字符串而不是标准输入或文件。
stringstream ssin(line);
//从字符串流 ssin 中读取数据,并将其存储到数组 a[] 的第 n 个位置。
//这个操作会跳过空格和回车,只读取其中的数字部分。这是因为流操作符 >> 在读取时会忽略空白字符(包括空格、换行符等),直到遇到下一个有效字符。
while (ssin >> a[n]) n++;
}
sort(a, a + n);
for (int i = 1; i < n; i++)
{
if (a[i] == a[i - 1]) res2 = a[i];
else if (a[i] - a[i - 1] != 1) res1 = a[i] - 1;
if (res1 && res2) break;
}
cout << res1 << " " << res2 << endl;
return 0;
}
但其实用cin也行。。
#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;
const int N = 10010;
int n, res1, res2;
int a[N];
int main()
{
int cnt;
cin >> cnt;
while (cin >> a[n]) n++;
sort(a, a + n);
for (int i = 1; i < n; i++)
{
if (a[i] == a[i - 1]) res2 = a[i];
else if (a[i] - a[i - 1] != 1) res1 = a[i] - 1;
if (res1 && res2) break;
}
cout << res1 << " " << res2 << endl;
return 0;
}
总结stringstream和sscanf
1.sscanf
头文件:string
注意:sscanf(str.c_str(), "%d%d%d", &a, &b, &c);
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int main()
{
int a, b, c;
string str;
//读入一行
getline(cin, str);
// str.c_str() 的作用是为了将 string 对象转换为 C 风格字符串
// 因为 sscanf 函数接受的是 C 风格的字符串作为参数
sscanf(str.c_str(), "%d%d%d", &a, &b, &c);
printf("a: %d, b: %d, c: %d", a, b, c);
return 0;
}
2.stringstream
头文件:sstream
注意:stringstream ssin(str);
#include <iostream>
#include <cstdio>
#include <sstream>
using namespace std;
int main()
{
int a, b, c;
string str;
getline(cin, str);
stringstream ssin(str);
ssin >> a >> b >> c;
printf("a: %d, b: %d, c: %d", a, b, c);
return 0;
}
文章讲述了C++中`getline`与`stringstream`以及`sscanf`在处理多行输入数据和读取整数数组的应用,同时介绍了两者之间的差异和适用场景。通过实例展示了如何使用这些方法读取数据并进行简单的数组排序。

2万+

被折叠的 条评论
为什么被折叠?



