从字符串提取整形(字符型)存入数组

本文展示了两个C++程序片段,分别演示了如何从用户输入的字符串中提取整数和字符,使用`getline`、`stringstream`和`vector`进行处理,并暂停程序执行。
摘要由CSDN通过智能技术生成

1提取整形

#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
    // 声明字符串变量 str 用于存储用户输入的一行字符串
    string str, temp;

    // 使用 getline 从标准输入流中读取一行字符串,并存储在变量 str 中
    getline(cin, str);

    // 声明整数向量 p 用于存储提取的整数
    vector<int> p;

    // 使用 stringstream 对象 input 将字符串 str 转换为输入流
    stringstream input(str);


    // 声明整数变量 i 用于暂存从字符串中提取的整数
    int i = 0;


    // 循环从输入流中读取整数,并将其存储在整数向量 p 中
    while (input >> i) {
        p.push_back(i);
    }

    // 循环遍历整数向量 p,并输出每个整数到控制台
    for (int i = 0; i < p.size(); i++)
    {
        cout << p[i];
    }

    // 输出换行符,使输出更清晰
    cout << endl;

    // 使用 system 函数暂停程序执行,等待用户手动关闭
    system("pause");

    // 返回 0 表示程序正常结束
    return 0;
}

2

#include <iostream>
#include <vector>
#include <sstream>

int main()
{
    std::string str, temp;
    
    // 从标准输入中获取一行字符串
    getline(std::cin, str);

    // 声明一个字符向量,用于存储提取的字符
    std::vector<char> characters;

    // 使用 stringstream 对象将字符串转换为输入流
    std::stringstream input(str);

    char c;
    // 逐字符读取输入流中的字符
    while (input >> c) {
        // 将字符添加到字符向量中
        characters.push_back(c);
    }

    // 使用循环遍历字符向量并输出每个字符到控制台
    for (char c : characters) {
        std::cout << c;
    }

    std::cout << std::endl;

    // 使用 system 函数暂停程序执行,等待用户手动关闭
    system("pause");

    // 返回 0 表示程序正常结束
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值