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  
相关推荐
CarIise3 分钟前
JavaScript进阶与轮播图实现 课堂笔记
开发语言·javascript·笔记
mayaairi9 分钟前
JS DOM节点操作完全指南:增删改查与性能优化
开发语言·javascript·性能优化
Demon--hx10 分钟前
多态实现原理
开发语言·c++
wanglei20070813 分钟前
消息队列的协作模式
开发语言·python
jimy131 分钟前
拷贝构造时,不用引用的话,按值传参会无限递归调用拷贝构造函数
开发语言
LccKyI35 分钟前
# C# 基础编程 面试题汇总(一)
开发语言·c#
CODER030438 分钟前
win11系统编译安装cuda版llama-cpp-python(踩完所有的坑)
开发语言·python·llama
神仙别闹43 分钟前
基于C语言+SQLite 实现(控制台+图形界面)图书管理系统
c语言·开发语言·sqlite
水饺编程1 小时前
第5章,[Win32 章节] :绘制填充区域
c语言·c++·windows·visual studio
何以解忧,唯有..1 小时前
LangChain 模型调用方法总结:invoke、batch、stream 的入参与出参
开发语言·langchain·batch