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  
相关推荐
明月醉窗台12 分钟前
Qt 入门 1 之第一个程序 Hello World
开发语言·c++·qt
Craaaayon24 分钟前
Java八股文-List集合
java·开发语言·数据结构·list
幻想趾于现实30 分钟前
C# Winform 入门(11)之制作酷炫灯光效果
开发语言·c#·winform
hy____12335 分钟前
类与对象(中)(详解)
开发语言·c++
wen__xvn40 分钟前
c++STL入门
开发语言·c++·算法
2301_794461571 小时前
多线程编程中的锁策略
java·开发语言
XYN611 小时前
【嵌入式学习3】基于python的tcp客户端、服务器
服务器·开发语言·网络·笔记·python·学习·tcp/ip
the_nov1 小时前
20.IP协议
linux·服务器·网络·c++·tcp/ip
只有月亮知道1 小时前
C++list常用接口和模拟实现
开发语言·c++
Epiphany心理1 小时前
R语言使用ggplot2作图
开发语言·r语言