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  
相关推荐
喵个咪30 分钟前
Qt 6 实战:C++ 调用 QML 回调方法(异步场景完整实现)
前端·c++·qt
立志成为大牛的小牛38 分钟前
数据结构——五十一、散列表的基本概念(王道408)
开发语言·数据结构·学习·程序人生·算法·散列表
机灵猫3 小时前
java锁:从 Mark Word 锁升级到 AQS
java·开发语言
阿波茨的鹅3 小时前
VSCode C++ 项目配置教程
c++·ide·vscode
扶尔魔ocy3 小时前
【QT opencv】手动去噪--网格化获取区域坐标
开发语言·qt·opencv
程序员与背包客_CoderZ4 小时前
C/C++版LLM推理框架Llama.cpp——入门与编码实战
c语言·开发语言·网络·c++·人工智能·语言模型·llama
喵了几个咪4 小时前
C++ IDE:最适合 C++ 初学者的 IDE 是什么?
开发语言·c++·ide
梅梅绵绵冰4 小时前
springmvc文件上传
java·开发语言
Hat_man_4 小时前
虚拟机Ubuntu22.04交叉编译Qt5.15.2(ARM64)
开发语言·qt
Boop_wu4 小时前
[Java 面试] 多线程1
java·开发语言