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  
相关推荐
纪念 2297 分钟前
C++ 算法模板与错题 模拟(一)
android·c++·算法
随流寻影10 分钟前
利用 C++ 实现二叉搜索树的增删查
开发语言·c++
总要学点什么1 小时前
第128篇:镜头光晕与高光——把逆光太阳晕成会躲山的光斑
开发语言·javascript·数码相机·microsoft·材质·cesium
Escalating_xu1 小时前
【COZE实战】插件与知识库(三):让智能体会查资料,也会使用工具
开发语言·网络·人工智能·ai
学逆向的1 小时前
C++多态 汇编分析
开发语言·汇编·c++·网络安全
阿凤212 小时前
学习java---流程控制篇
java·开发语言·学习
ShineWinsu2 小时前
对于Qt:QSound的解析
c++·qt·面试·音频·笔试·客户端·qsound
derek19972 小时前
软考软件设计师:白盒覆盖哪条最弱、McCabe 复杂度怎么数、单元测试最能发现什么错
c语言·c++·计算机网络·软件工程·学习方法
Code_Solitude2 小时前
c语言:期末最后一道大题模拟
c语言·开发语言
李松桃2 小时前
Python爬虫基础
开发语言·爬虫·python·get请求使用方法·post请求使用方法