AcWing 1204. 错误票据(string的转化,枚举)

这篇博客介绍了如何使用C++中的stringstream函数将字符串转化为整数,并在读取数组时避免内存溢出的问题。通过示例代码展示了如何在处理连续和断号数字时找到重号和断号,以及在读取和操作字符串时的注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

思路:
主要难在把 string 转化为 int ,本题用到 sstream 函数进行转化

公式:
if (a[i] == a[i - 1]) res2 = a[i]; // 找到重号
else if (a[i] >= a[i - 1] + 2) res1 = a[i] - 1; // 找到断号

stringstream 函数的一些用法

注意用完 stringstream 中的函数时,要clear 一下 ,如:ss.clear();
注意清内存空间: ss.clear(); ss.str(" ");
在这里插入图片描述

一个与本题输入相似的代码,可以学习人家的写法

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
 
int main()
{
    string s;
    stringstream ss;
    int n;
 
    cin >> n;
    getline(cin, s);  //读取换行
    for (int i = 0; i < n; i++)
    {
        getline(cin, s);
        ss.clear();
        ss.str(s);
 
        int sum = 0;
 
        while (1)
        {
            int a;
 
            ss >> a;
            if(ss.fail())
                break;
            sum += a;
        }
        cout << sum << endl;
    }
 
    return 0;
}

当需要将数字放在一个string中的写法

#include<sstream> 
#include<bits/stdc++.h>

using namespace std;
 
int main()
{
    double x=7856.96;
	int xx=236;
	string e=" ";
	
    string s;
    stringstream ss;
    ss<<x;
    ss>>s;
    cout<<s<<endl;
    
    ss.clear();//将 ss 重置,不要下面没办法赋值。 
    ss.str(" ");//清理内存 
    string c;
    ss<<xx;
    ss>>c;
    s=s+e+c;
	cout<<s<<endl;
    
    return 0;
}

代码:

#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
#include<vector>

using namespace std;

const int N = 10010;

int n;
int a[N];

int main()
{
    int cnt;
    cin >> cnt;
    string line;

    getline(cin, line); // 忽略掉第一行的回车
    while (cnt -- )
    {
        getline(cin, line);
        
        //为了使字符串转化成整型的函数 
        stringstream ss;
        ss.clear();
        ss.str(line);
        
        //还可以写成这样
		/*
		stringstream ss(line); 
		
		*/ 
        
        while(ss>>a[n]) n++;//如果写成 ss>>a[n++] 会造成内存爆表 
        //ss>> 只会吸收 int 类型的值 
    }

    sort(a, a + n);

    int res1, res2;
    for (int i = 1; i < n; i ++ )
        if (a[i] == a[i - 1]) res2 = a[i];  // 找到重号
        else if (a[i] >= a[i - 1] + 2) res1 = a[i] - 1; // 找到断号

    cout << res1 << ' ' << res2 << endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值