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  
相关推荐
人邮异步社区1 小时前
如何系统地学习 C++ 语言?
开发语言·c++·学习
欧特克_Glodon2 小时前
OpenCV计算机视觉开发入门与实践<二十>:非线性变换灰度变换
c++·人工智能·opencv·计算机视觉
知识分享小能手2 小时前
概理论与数理统计学习教程,从入门到精通,在数理统计中应用R软件(21)
开发语言·学习·r语言
Data_Journal2 小时前
Playwright vs Selenium:哪个是最佳无头浏览器
开发语言·python·scrapy·microsoft·编辑器
Chester_19992 小时前
CSP202104C.DHCP服务器
开发语言·程序人生·蓝桥杯
跨境技工小黎2 小时前
LLM蜜罐系统是什么?AI爬虫如何精准绕过?
开发语言·人工智能·python
-今昭-2 小时前
OpenStack Dashboard 部署与图形化创建云主机实战指南
开发语言·php
lswzw3 小时前
K8s容器网络排查实战:从宿主机穿透命名空间定位端口监听问题
开发语言·docker·容器
zh73144 小时前
typephp的编译核心phpx原理解析
android·java·开发语言