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  
相关推荐
艾利克斯冰2 分钟前
Java 设计模式-行为型模式(更新中)
java·开发语言·设计模式
倒霉蛋小马15 分钟前
Java新特性:record关键字
java·开发语言
浪客灿心28 分钟前
项目篇:模块设计与实现
数据库·c++
budingxiaomoli37 分钟前
Spring日志
java·开发语言
牛油果子哥q40 分钟前
【C++ STL vector】C++ STL vector 终极精讲:动态数组底层原理、两倍扩容机制、迭代器失效、增删查改、性能剖析与工程避坑指南
开发语言·c++
贩卖黄昏的熊1 小时前
flex 布局快速梳理
开发语言·javascript·css3·html5
天天进步20151 小时前
Python全栈项目--校园智能宿舍管理系统
开发语言·python
CodeStats1 小时前
从 CPU 指令到 JVM 进程:彻底讲透 Java 执行 main 方法时,类加载、主线程、栈帧入栈的完整底层逻辑
java·linux·开发语言
阿正的梦工坊2 小时前
【Rust】09-泛型、Trait 与生命周期基础
开发语言·rust·c#