c++ - 如何从没有额外分隔符的字符串中构建逗号分隔列表?
问题描述
所以我正在尝试做这样的事情:
输入:
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, ,
有人可以帮我解决这个问题吗?
解决方案
这应该解决它:
#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
推荐阅读
- c++ - 在小部件已经初始化后如何设置小部件的父级(例如,如果小部件是函数调用的参数)?
- concatenation - 有没有办法在 [onshow; 中连接多行?如果 [var.x]!='0'; 然后'这里多行';else '']
- gcc - 如何更改 OpenMPI 的编译器
- python-3.x - 如何检查进程之间腌制的数据
- windows - 如何以编程方式获取 Windows 显示器/监视器/屏幕标识号?
- python-3.x - Python - 如何创建连接命令
- java - 使 Mapbox 标记可点击并返回标记的 ID
- azure-devops - Azure DevOps - 应用服务 - 并行插槽交换
- c++ - 设置以改进 Visual Studio 难以理解的编译/构建错误:MSB6006:“CL.exe”退出代码 2
- kubernetes - 如何使用 rabbitmqctl 从 RabbitMQ Kubernetes 集群外部访问?