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 分钟前
list实现(7)(上)
c++
CHANG_THE_WORLD6 分钟前
Python 字符串全面解析
开发语言·python
不会c嘎嘎15 分钟前
深入理解 C++ 异常机制:从原理到工程实践
开发语言·c++
崇山峻岭之间27 分钟前
C++ Prime Plus 学习笔记026
c++·笔记·学习
永远都不秃头的程序员(互关)35 分钟前
C语言 基本语法
c语言·开发语言
永远都不秃头的程序员(互关)1 小时前
Java核心技术精要:高效实践指南
java·开发语言·性能优化
是Dream呀1 小时前
Python圣诞特辑:打造一棵会唱歌、会下雪的魔法圣诞树
开发语言·python·pygame
未来之窗软件服务1 小时前
幽冥大陆(四十一)美萍V10酒店门锁SDK C#语言仙盟插件——东方仙盟筑基期
开发语言·c#·仙盟创梦ide·东方仙盟·东方仙盟sdk·酒店智能门锁·东方仙盟 vos 智能浏览器
赖small强1 小时前
【Linux C/C++开发】Linux 平台 Stack Protector 机制深度解析
linux·c语言·c++·stack protector·stack-protector·金丝雀机制
Wild_Pointer.2 小时前
环境配置指南:全景目录
c++