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  
相关推荐
栈溢出了5 分钟前
Redis repl_backlog 学习笔记
java·开发语言·redis·学习
urkay-14 分钟前
Kotlin Flow分类
android·开发语言·kotlin
并不喜欢吃鱼20 分钟前
从零开始 C++----- 十五.一文吃透 C++ 异常:try-catch、栈展开、自定义异常、异常安全 noexcept 底层全剖析
java·开发语言·jvm
盐焗鹌鹑蛋27 分钟前
【C++】AVL树
c++
gr95ZS6E632 分钟前
基础入门java安全(一)--CC1基础分析
开发语言·python
北京阿法龙科技有限公司1 小时前
AR智能眼镜安防应用核心指标:识别距离筑牢防线
java·开发语言·ar
杜子不疼.1 小时前
【C++】继承—C++的秘密武器,get父类的智慧
开发语言·c++
ShineWinsu1 小时前
对于Linux:基于UDP实现简单聊天室功能
linux·c++·面试·udp·笔试·进程·简单聊天室
chase_my_dream1 小时前
2D-SLAM 真实数据处理与多传感器工程落地:时间同步、异常过滤、标定对齐和系统调试
c++·人工智能·2d-slam
阿pin1 小时前
Android随笔-View绘制流程
android·开发语言·view