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  
相关推荐
IT=>小脑虎2 分钟前
2026版 Python零基础小白学习知识点【基础版详解】
开发语言·python·学习
wjs202412 分钟前
抽象工厂模式
开发语言
lly20240613 分钟前
SVG 模糊效果详解
开发语言
期待のcode15 分钟前
Java虚拟机类加载机制
java·开发语言
Learner22 分钟前
Python运算符
开发语言·python
一晌小贪欢26 分钟前
Python 精确计算:告别浮点数陷阱,decimal 模块实战指南
开发语言·python·python入门·python3·python小数·python浮点数
superman超哥27 分钟前
Rust 范围模式(Range Patterns):边界检查的优雅表达
开发语言·后端·rust·编程语言·rust范围模式·range patterns·边界检查
程序员zgh40 分钟前
Linux 系统调用
linux·运维·服务器·c语言·c++·系统安全
天若有情67343 分钟前
打破思维定式!C++参数设计新范式:让结构体替代传统参数列表
java·开发语言·c++
初晴や1 小时前
【C++】图论:基础理论与实际应用深入解析
c++·算法·图论