c++ - 如何以简单的方式从 C++ 中的循环中删除最后一个逗号?

标签 c++ while-loop

<分区>

此程序用于打印素数直到给定输入并用逗号分隔每个素数。

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");
}

它只是删除质数输入的最后一个逗号,而不是任何其他输入。我该如何解决这个问题?

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 = ",";
}

不需要对所有情况进行检查,例如 vector 是否为空。

如果一开始就接受一个额外的空格,直接把字符串换成char,性能会提升更多。

关于c++ - 如何以简单的方式从 C++ 中的循环中删除最后一个逗号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33054983/

相关文章:

java - 无法访问的代码 while 循环

python - 房屋和存款的年利息

c++ - 在不更改默认打印机的情况下使用 IE 控件打印到特定打印机

c++ - 在 MacOS 10.9 (Mavericks) 上构建 Boost.Python 应用程序

c++ - STL 中令人烦恼的解析 scott meyers

java - 我的 java 程序无法正常运行。

JAVA While Loop 无法识别条件中的 String.equals()

c++ - 阻止 UDP 数据包在接收缓冲区快满时被部分截断

c++ - 如何在 std::map 声明中声明自定义排序函数?

C编程: Sum of a sequence of integers until zero and prints the sum of two multiplied integers