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  
相关推荐
覆东流3 小时前
7.Java数组
java·开发语言·后端
码行山野赴时序归途3 小时前
三道经典数组题:从暴力到最优的算法思维
c语言·开发语言·数据结构·算法·leetcode
lzhdim4 小时前
提高 SQL 语句执行速度的方法
java·开发语言·数据库·sql·oracle
JavaPub-rodert4 小时前
王仕宇在 Go Context 如何解决协程泄漏与超时控制
开发语言·后端·golang·iphone·javapub·王仕宇
ly76895 小时前
JavaScript 从入门到进阶:核心语法、异步编程与工程化实践
开发语言·javascript·ecmascript
落魄大学生之流水线上谋生计5 小时前
Java锁全面指南:从基础概念到企业级应用
java·开发语言
for_ever_love__6 小时前
python基础语法学习: 闭包
开发语言·python·学习·闭包
ly76896 小时前
Python 全面入门:从核心语法到工程实践
开发语言·python
艾伦_耶格宇7 小时前
【AI】-4 OpenCode Go 接入 Obsidian 完整指南
运维·开发语言·人工智能·agent·opencode
码匠许师傅7 小时前
【C++ 面试真题】30. 聊聊 C++ 的互斥锁与读写锁
java·c++·面试