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  
相关推荐
闲猫14 分钟前
LangChain / Core components / Models
开发语言·python·langchain
ComputerInBook1 小时前
c 和 c++ 中的宏块(macro)
c语言·c++··宏块·宏指令
AA陈超2 小时前
004 T02 - 俯视角摄像机系统 设计文档
网络·c++·ue5·虚幻引擎
-银雾鸢尾-2 小时前
C#中的索引器
开发语言·c#
bu_shuo2 小时前
c与cpp中的argc和argv
c语言·c++·算法
蓝创精英团队2 小时前
VCPKG 跨平台C++ 库管理器
c++·vcpkg
Qlittleboy2 小时前
PHP的接口参数传递的过多,max_input_vars = 5000
开发语言·php
Aurorar0rua2 小时前
CS50 x 2024 Notes Algorithms - 02
c语言·开发语言·学习方法
en.en..2 小时前
冒泡排序与选择排序完整对比解析
开发语言·数据结构·算法·c#·排序算法
兰令水2 小时前
hot100【acm版】【2026.7.18打卡-java版本】
java·开发语言·算法