特殊数据读入 (stringstream, sscanf, getline)

文章讲述了C++中`getline`与`stringstream`以及`sscanf`在处理多行输入数据和读取整数数组的应用,同时介绍了两者之间的差异和适用场景。通过实例展示了如何使用这些方法读取数据并进行简单的数组排序。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

getline+ stringstream

例题:错误票据
getlinestringstream将多行数据读入一个数组中

#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;
}

总结stringstreamsscanf

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;
}

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值