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  
相关推荐
whcyhhh1 分钟前
头歌实践教学平台:大数据存储2023(十三3)
大数据·开发语言·python
2601_9561219721 分钟前
线性DP(入门)
c++·算法·动态规划
彷徨而立29 分钟前
【C/C++】多线程读写普通 int 变量的一些问题
java·c语言·c++
Freak嵌入式1 小时前
树莓派 Pico GPIO 深度解析:从 MCU 架构到寄存器控制,底层原理与实践指南
java·开发语言·科技·单片机·嵌入式硬件·架构
蒸蒸yyyyzwd1 小时前
cpp web server 面试可能问题总结
c++·笔记·八股
啊啊啊啊啊!!!!1 小时前
【c++】map和set的使用
开发语言·c++
hu9245195591 小时前
Matlab保护源代码—P文件和exe文件详细解析
开发语言·matlab
for_ever_love__1 小时前
python爬虫: GET请求与POST请求
开发语言·爬虫·python·网络编程
Freak嵌入式1 小时前
实战对比:用 mpremote/Putty/MobaXterm 连接树莓派 Pico REPL,谁更省心?
java·大数据·开发语言·科技·单片机·嵌入式硬件
ttwuai1 小时前
Go 后台管理系统组件库文档怎么写,才不会坑后续维护?
开发语言·javascript·golang