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  
相关推荐
fangzhanpeng1685 分钟前
(前端)2.js变量作用域样例
开发语言·前端·javascript
mqiqe3 小时前
线程调度与 Schedulers:Project Reactor 并发模型的核心引擎
java·开发语言·网络
xixiaoyunya4 小时前
JavaScript 异步编程全解析:从回调地狱到 async/await 的演进之路
开发语言·javascript·ecmascript
精英的英4 小时前
记一次 Qt5 Language Server 开发
开发语言·vscode·qt
烧酒同学5 小时前
【C++】记录size of std::vector的巧妙坑
开发语言·c++·图形渲染
周周哈哈哈5 小时前
线程创建、执行、退出、回收
java·开发语言
gb42152875 小时前
python中Web应用服务器
开发语言·前端·python
萧瑟余晖6 小时前
Java深入解析篇三十六之分布式系统详解
java·开发语言·分布式
ZJU_统一阿萨姆6 小时前
【推理优化进阶】调度器的数学内核:排队论、SLO 与在线决策
开发语言·人工智能·语言模型·系统架构·vllm
平常心的技术小牛6 小时前
Qt-快速上手-QTextCursor
开发语言·qt