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  
相关推荐
张忠琳3 分钟前
【Go 1.26.4】Golang Map 深度解析
开发语言·后端·golang
Vertira3 分钟前
如何对QT开发的软件进行打包[已解决]
开发语言·qt
AI人工智能+电脑小能手6 分钟前
【大白话说Java面试题 第110题】【并发篇】第10题:CAS 存在哪些问题?
java·开发语言·面试
石一峰69914 分钟前
C 语言函数设计模式实战经验
c语言·开发语言·设计模式
sitellla20 分钟前
Pydub:用 Python 处理音频,不写废话
开发语言·python·其他·音视频
xingyuzhisuan28 分钟前
缓存命中率提升方案:从 30% 优化至 82% 全流程优化记录
java·开发语言·缓存·ai
郑洁文34 分钟前
基于Python的恶意流量监测系统的设计与实现
开发语言·python
AI玫瑰助手36 分钟前
Python流程控制:for循环与range函数的搭配使用
开发语言·python·信息可视化
anew___39 分钟前
2026年Python爬虫技术完全指南:从入门到实战
开发语言·爬虫·python
Penfy_Z40 分钟前
【Python LLM 调用踩坑】Connection error 终极解决方案!npm 代理导致阿里云通义千问接口连接失败
开发语言·python·npm