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  
相关推荐
K 旺仔小馒头29 分钟前
优选算法:01 双指针巧解移动零问题
c++·算法·刷题
weixin_445476681 小时前
Java并发编程——synchronized的实现原理与应用
java·开发语言·并发·synchronized
yi碗汤园1 小时前
【超详细】C#自定义工具类-StringHelper
开发语言·前端·unity·c#·游戏引擎
sali-tec1 小时前
C# 基于halcon的视觉工作流-章49-网面破损
开发语言·图像处理·算法·计算机视觉·c#
AlexMercer10121 小时前
Ubuntu从零开始配置Git
c++·git·ubuntu·gitee
YuanlongWang1 小时前
c# ABP vNext 框架详解及其模块化开发思想介绍
开发语言·c#
张人玉2 小时前
WPF布局控件(界面骨架核心)
开发语言·c#·wpf·布局控件
闲人编程2 小时前
使用MLflow跟踪和管理你的机器学习实验
开发语言·人工智能·python·机器学习·ml·codecapsule
看兵马俑的程序员2 小时前
RAG实现-本地PDF内容加载和切片
开发语言·python·pdf
专注前端30年2 小时前
【JavaScript】reduce 方法的详解与实战
开发语言·前端·javascript