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  
相关推荐
灵晔君39 分钟前
C++标准模板库(STL)——list的模拟实现
c++·list
AI_56781 小时前
接口测试“零基础通关“:Postman从入门到自动化测试实战指南
开发语言·lua
是Yu欸1 小时前
Rust 并发实战:从零构建一个内存安全的“番茄时钟”
开发语言·安全·rust
Justinyh2 小时前
1、CUDA 编程基础
c++·人工智能
应用市场2 小时前
Qt QTreeView深度解析:从原理到实战应用
开发语言·数据库·qt
ooooooctober2 小时前
PHP代码审计框架性思维的建立
android·开发语言·php
864记忆2 小时前
Qt Widgets 模块中的函数详解
开发语言·qt
white-persist2 小时前
差异功能定位解析:C语言与C++(区别在哪里?)
java·c语言·开发语言·网络·c++·安全·信息可视化
q***72872 小时前
Golang 构建学习
开发语言·学习·golang
hmbbcsm2 小时前
练习python题目小记(五)
开发语言·python