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  
相关推荐
t1987512810 分钟前
基于多尺度特征融合与自适应权重优化的水下图像对比度与边缘增强MATLAB方法
开发语言·matlab
像污秽一样40 分钟前
算法设计与分析-算法效率分析基础-习题1.1
c语言·数据结构·c++·算法
chilavert3181 小时前
程序员面试经典问题解答:java篇-2
开发语言·python
senijusene1 小时前
TCP并发服务器:poll和epoll的多路复用
开发语言·php
浅碎时光8071 小时前
Qt (按钮/显示/输入/容器类控件 布局管理器)
开发语言·qt
bubiyoushang8881 小时前
OFDM系统信道估计MATLAB实现(LS、MMSE、DCT、LRMMSE方法)
开发语言·网络·matlab
Felven1 小时前
C. Dora and Search
c语言·开发语言
John Song3 小时前
Python创建虚拟环境的方式对比与区别?
开发语言·python
搞程序的心海3 小时前
Python面试题(一):5个最常见的Python基础问题
开发语言·python
2401_8846022710 小时前
程序人生-Hello’s P2P
c语言·c++