如何在不使用结尾的分隔符的情况下从字符串构建逗号分隔的列表? [英] How to build a comma delimited list from strings w/o the extra delimiter at the end?

查看:86
本文介绍了如何在不使用结尾的分隔符的情况下从字符串构建逗号分隔的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试执行以下操作:

So i'm trying to do something like this:

输入:

hi my name is clara

预期输出:

hi, my, name, is, clara

我的程序如下:

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

int main()
{

    string str;

    getline(cin, str);

    istringstream ss(str);
    do {
        string word;
        ss >> word;
        cout << word << ", ";
    } 
    while (ss);
}

但是输出看起来像这样

hi, my, name, is, clara, ,

有人可以帮我解决这个问题吗?

Can someone help me fix this?

推荐答案

这应该解决该问题:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {

    string str;

    getline(cin, str);
    
    string word;
    istringstream ss(str);
    bool firstIteration = true;
    while(ss >> word) {
        if(!firstIteration) {
            cout  << ", ";
        }
        cout << word;
        firstIteration = false;
    };
}

检查工作演示请在这里

我在许多编程中都使用了这种习惯用法(模式?)。语言以及需要从列表(如输入)构造定界输出的所有类型的任务。让我用伪代码给出摘要:

I am using this idiom (pattern?) in many programming languages, and all kind of tasks where you need to construct delimited output from list like inputs. Let me give the abstract in pseudo code:

empty output
firstIteration = true
foreach item in list
    if firstIteration
        add delimiter to output
    add item to output
    firstIteration = false

在某些情况下,甚至可以完全忽略 firstIteration 指标变量:

In some cases one could even omit the firstIteration indicator variable completely:

empty output
foreach item in list
    if not is_empty(output)
        add delimiter to output
    add item to output

这篇关于如何在不使用结尾的分隔符的情况下从字符串构建逗号分隔的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆