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  
相关推荐
黑马程序员毕设12 分钟前
基于Java的仪器管理系统设计与实现
java·开发语言·spring boot·后端·微信小程序
平头哥AI13 分钟前
Day 13 | 一个函数回两个值:Go 的 error 是从哪冒出来的
开发语言·后端·golang
asdzx6732 分钟前
Python 实现 PDF 文本查找与高亮标注
开发语言·python·pdf
zander25835 分钟前
LeetCode 1143. 最长公共子序列
开发语言·python·算法
Sumerking37 分钟前
llc_control.c 专项评审(v3 更新版)
c语言·开发语言·算法·obc
棣廷1 小时前
初识Python面向对象
java·开发语言
研☆香1 小时前
js中 onload 事件的用法
开发语言·javascript·ecmascript
软行1 小时前
LeetCode 每日一题 3876. 构造奇偶一致的数组 II
c++·算法·leetcode
xiancai_xianyu1 小时前
想把数据模型一次建完美再上AI?会一直卡在建模里
开发语言·人工智能·php·数据模型·语义层·本体建模·企业知识网络
繁星蓝雨1 小时前
C++设计原理———重载(extern “C“的由来、顺序依赖、语义依赖、overload、名称修饰符、对象操作、运算符重载、新增运算符、枚举和布尔类型)
c语言·c++·extern c·overload·重载·语义依赖·顺序依赖