C++ 获取一整行(一行)字符串并转换为数字

代码很简单,主要是自己总是忘记,记录一下:

cpp 复制代码
#include <iostream>
#include <cstdlib>
#include <cstring>

#include <string>
#include <vector>
#include <sstream>

using namespace std;

void print_int_arr(vector<int> nums)
{
    cout << "nums: ";
    for (int num : nums)
    {
        cout << num << "  ";
    }

    cout << endl;
}

int main()
{
    string str1, str2;

    // 获取一整行字符串
    getline(cin, str1);
    getline(cin, str2);

    vector<int> num1, num2;

    cout << "demo: " << endl;
    cout << str1 << endl;
    cout << str2 << endl;

    int num;

    // 转换数字
    stringstream ss1(str1);
    while (ss1 >> num)
    {
        num1.emplace_back(num);
    }

    stringstream ss2(str2);
    while (ss2 >> num)
    {
        num2.emplace_back(num);
    }

    print_int_arr(num1);
    print_int_arr(num2);

    return 0;
}

结果如下:

bash 复制代码
[chen@localhost]$ ./a.out 
11 22 33 1 0 21
23
demo: 
11 22 33 1 0 21
23
nums: 11  22  33  1  0  21  
nums: 23  
相关推荐
熊猫钓鱼>_>几秒前
普通用户视角的端侧智能体验手记【鸿蒙心迹】
开发语言·人工智能·华为·智能手机·性能优化·ai编程·harmonyos
瑞雪兆丰年兮2 分钟前
JavaWeb-day13-SpringBootWeb事务管理&AOP
java·开发语言·springboot·javaweb·事务·web·aop
布莱克6052 小时前
Swift 常量详解:从 let 到编译期优化
服务器·开发语言·ssh·swift·常量·let
布莱克6052 小时前
Swift 可选类型(Optionals)详解:从原理到实战
开发语言·安全·ssh·swift·optional·可选类型
老歌老听老掉牙2 小时前
案例 7:二维 Rosenbrock 函数最小值(香蕉函数)
c++·pso
Severus_black3 小时前
【C++初阶】Stack、Queue算法题大练兵!
c语言·c++·算法·stl
瑞雪兆丰年兮4 小时前
JavaWeb-day14-SpringBootWeb原理篇
java·开发语言·spring boot·spring·bean·mybatis·javaweb
SomeOtherTime6 小时前
Rust生命周期介绍(AI回答)
开发语言·后端·rust
程序猿打工仔6 小时前
计算机基础(C语言)考编、专技岗
c语言·开发语言·算法
喵本喵叁肆6 小时前
Rényi 差分隐私:把隐私损失看成一族矩(英文原题:Rényi Differential Privacy (CSF 2017))
开发语言·r语言