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  
相关推荐
fqbqrr15 分钟前
2606C++,方便的调试类
c++
ZC跨境爬虫17 分钟前
跟着 MDN 学 JavaScript day_2:JavaScript 初体验
开发语言·前端·javascript·学习·ecmascript
我不是懒洋洋21 分钟前
从零实现一个RPC框架:远程调用与服务治理
c++
困意少年34 分钟前
从统一初始化到移动语义:C++11 为什么是现代 C++ 的起点
c++
Jun62641 分钟前
QT(3)-线程中使用控件
开发语言·qt
stolentime42 分钟前
CF2066D1 Club of Young Aircraft Builders (easy version)题解
c++·算法·动态规划·组合数学
xiaoshuaishuai843 分钟前
C# AvaloniaUI ProgressBar用法
开发语言·c#
咋吃都不胖lyh1 小时前
LangGraph标准构建示例
开发语言·python
Jun6261 小时前
QT(1)-C/C++库生成和调用
c语言·开发语言·c++·qt
小欣加油1 小时前
leetcode41 缺失的第一个正数
数据结构·c++·算法·leetcode