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  
相关推荐
yiangL_11 小时前
课后作业4:基于 Python 的古诗词词云可视化(P205)
开发语言·python
JosieBook12 小时前
【鸿蒙开源】把 Windows 任务栏上的流量表搬到鸿蒙 PC:TrafficMonitor 1.86 的 C++ 内核移植实践
c++·windows·harmonyos
Huangjin007_13 小时前
【C++ 算法竞赛篇】STL 常用知识点速通指南
c++·算法
geovindu13 小时前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
skywalk816314 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness
敲上瘾14 小时前
Qt控件通用属性:geometry、qrc资源到QSS样式表等
开发语言·c++·qt·ui
炸膛坦客15 小时前
单片机/C/C++八股:(三十三)取别名
c语言·c++·单片机
听情歌落俗15 小时前
嵌入式学习1-C语言基础语法与STM32实践
c语言·开发语言
小飞在努力16 小时前
【实现负载均匀在线判题⑤】MVC 架构搭建与 Model 题目数据模块实现
c语言·开发语言·c++·笔记·后端
ShineWinsu16 小时前
对于Qt:QFontDialog的解析
c++·qt·面试·gui·字体·客户端·qfontdialog