C++处理输入文本行(一行中包含多个字符串)

9 篇文章 0 订阅

第一种方法:使用cin.get(ch),循环检查输入缓冲区中的每个字符是否为空格、换行符,并进行分支处理,代码如下所示:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    vector<string> arr;
    string temp;
    char ch;
    
    while(cin.get(ch)) {
        if((ch != ' ') && ch != '\n') {
            temp += ch;
        }
        else if(ch == ' ') {
            arr.emplace_back(temp);
            temp.clear();
        }
        else {
            arr.emplace_back(temp);
            break;
        }
    }
    for(string str : arr) {
        cout << str <<endl;
    }

    return 0;
}

运行结果(第一行为输入,回车后,其余行为输出):

abc def ghi
abc
def
ghi

第二种方法:使用cin>>temp(将字符串保存到一个临时变量,并复制到数组中)、使用cin.get()循环检查在输入一个字符串之后是否输入换行结束,代码如下所示

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    vector<string> arr;
    string temp;
    char ch;

    while(cin >> temp) {
        arr.emplace_back(temp);
        if((ch = cin.get()) == '\n') {
            break;
        }
    }
    
    for(string str : arr) {
        cout << str <<endl;
    }

    return 0;
}

运行结果(第一行为输入,回车后,其余行为输出):

abc def ghi
abc
def
ghi
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值