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  
相关推荐
我不是疯子是傻子40 分钟前
Qt CAN通信周期发送抖动?实测定时器精度校准与时间戳补偿方案
开发语言·数据库·qt
IT爱学堂1 小时前
尚硅谷 - 2025年3月Java+AI大模型应用开发
java·开发语言·人工智能
有点。1 小时前
C++认识数
开发语言·c++
2023自学中2 小时前
Qt 简易聊天室(第二篇),单线程 改为 多线程,方便后续增加文件传输功能
c++·qt
W_326003 小时前
Python文件进阶:一维数据与 CSV 文件读写
开发语言·python
Tyler_TXZ3 小时前
C++C语言之——二叉树
c语言·开发语言·数据结构·c++·二叉树
有点。3 小时前
C++二叉树二(练习题)
数据结构·c++·算法·图论
不会代码的小猴3 小时前
C++新增关键字
开发语言·c++·笔记
yaoxin5211233 小时前
497. Java 反射 - 使用反射读取注解
java·开发语言·python
2019一路前行4 小时前
Python 函数式编程
开发语言·python