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  
相关推荐
大尚来也18 分钟前
HTML5 Web Worker:彻底解决JS阻塞页面卡顿问题
开发语言
sycmancia28 分钟前
Qt——复习篇painter
开发语言·qt
旖旎夜光30 分钟前
LeetCode 738:单调递增的数字(贪心算法) —— 题解
数据结构·c++·算法·leetcode·贪心算法
赵钰老师30 分钟前
R语言数据统计分析与ggplot2高级绘图
开发语言·数据分析·r语言
旖旎夜光39 分钟前
LeetCode 1262:可被三整除的最大和 (贪心算法)—— 题解
数据结构·c++·算法·leetcode·贪心算法
多弗朗皮卡丘1 小时前
C语言梦开始的地方3
c语言·开发语言
Bonnie_12151 小时前
08-JUC并发基础-AQS-补充共享锁
java·开发语言
qq_401700411 小时前
Qt 程序启动太乱?重新设计你的 Application 生命周期
开发语言·qt
蒸蒸yyyyzwd1 小时前
cpp 选手转 ai infra 后端秋招学习笔记 day1
c++·transformer
A_cainiao_A1 小时前
【ggml系列】【第四篇】ggml_graph_compute 多线程计算引擎与算子分发源码深度解析
开发语言·c++·矩阵