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  
相关推荐
Wang's Blog11 小时前
Go-Zero 项目开发47:自研微服务框架的必要性与核心结构设计
开发语言·微服务·golang
白鸽(二般)11 小时前
MinIO Java Client API
java·开发语言
hPw0eKIqD11 小时前
C++ 模板参数推导问题小记(非推导上下文)
开发语言·c++
程序员爱德华12 小时前
Python与C++:异同点对比
c++·python
临床数据科学和人工智能兴趣组12 小时前
要使用 R Markdown,首先需要安装 R 和 RStudio,接着安装 rmarkdown 包
开发语言·数据挖掘·数据分析·r语言·r语言-4.2.1
Nebula嵌入式12 小时前
【C语言】09-深入解析main函数
linux·c语言·开发语言·嵌入式
神罚天下ET14 小时前
c# ACME client (补充)
开发语言·c#
小灰灰搞电子15 小时前
Qt 实现魔法导航菜单源码分享
开发语言·qt
持敬chijing15 小时前
Python概述
开发语言·python
888CC++15 小时前
C语言与C++的区别:从面向过程到面向对象
java·c语言·c++