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  
相关推荐
看浪的路人6 分钟前
第3讲:代码补全引擎
开发语言·windows·python
SNAKEpc1213815 分钟前
OpenGL(十一)- 变换管线
c语言·c++·算法·矩阵·图形渲染
小小龙学IT26 分钟前
Day 26-27 项目实战:从零构建一个高并发聊天室(epoll + 线程池)
linux·服务器·c语言·开发语言·网络
牢姐与蒯36 分钟前
c++高级数据结构之图(基本概念,存储结构,BFS,DFS,最小生成树)
数据结构·c++·
我就是妖怪42 分钟前
【无标题】
开发语言
c238561 小时前
MySQL 基础用法(下):查询进阶与核心特性
android·c语言·c++·mysql
0566461 小时前
Python高级——迭代器
开发语言·python·学习
初级代码游戏1 小时前
iOS开发 Swift 速记4:函数与闭包
开发语言·ios·swift
码匠许师傅1 小时前
【C++ 面试真题】 C++ 中的 static 有什么作用?
c++·面试
郭涤生2 小时前
C++ 零拷贝(Zero-Copy)
linux·开发语言·c++