首页 > 解决方案 > 如何从没有额外分隔符的字符串中构建逗号分隔列表?

问题描述

所以我正在尝试做这样的事情:

输入:

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, ,

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

标签: c++stringlistdelimiter

解决方案


这应该解决它:

#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;
    };
}

请在此处查看工作演示。


我在许多编程语言中使用这个习语(模式?),以及所有需要从列表(如输入)构造分隔输出的任务。让我用伪代码给出摘要:

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

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

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

推荐阅读