How can I remove the last comma from a loop in C++ in a simple way?(如何以简单的方式从 C++ 的循环中删除最后一个逗号?)
问题描述
这个程序用于打印素数直到给定的输入并用逗号分隔每个素数.
This program is for printing prime numbers till the input given and separating every prime number with a comma.
void main(){
int N, counter=0, isPrime;
int k, j;
cout << "Enter maximum range: ";
cin >> N;
for (j=2; j<=N; j++){
isPrime = 0;
k = 2;
while (k<j){
if (j%k==0){
isPrime++;
}
k++;
}
if (isPrime==0){
if (k==N){
cout << j;
}
else{
cout << j << ",";
}
counter++;
}
}
cout << endl;
system("pause");
}
它只删除素数输入的最后一个逗号,而不删除任何其他输入.我该如何解决这个问题?
It is only removing the last comma for prime number inputs, not for any other input. How can I fix this?
Input: 23
Output: 2,3,5,7,11,13,17,19,23
Input: 8
Output: 2,3,5,7,
Input: 9
Output: 2,3,5,7,
推荐答案
没必要if then else那么多:
std::string delim = "";
for( auto&& item : vec )
{
std::cout << delim << item;
delim = ",";
}
不需要对所有情况进行检查,例如向量是否为空.
No checking is needed for all cases, like the vector is empty or not.
如果在开头接受一个额外的空格,只需将字符串替换为char,那么性能会得到更大的提升.
If you accept an extra space in the beginning, just replace the string to char, and then the performance will be improved even more.
这篇关于如何以简单的方式从 C++ 的循环中删除最后一个逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何以简单的方式从 C++ 的循环中删除最后一个逗号?
基础教程推荐
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
