首页 > 解决方案 > 使用数组和布尔值在输出未知时从输出中删除逗号

问题描述

如何删除输出末尾的逗号。但是在这里我不知道最终输出是什么,因为数组的元素是由用户输入的。所以最后一个数组可以是奇数也可以是偶数,并且它是未知的。我可以使用布尔值、数组和决策。我不允许使用指针或结构,因为我没有学过。

#include<iostream>
using namespace std;

int main()
{
    int array[100], Number;

    cout << "\nEnter the size of an array (1-20):";

    cin >> Number;

    if (Number <= 20 && Number > 0)
    {
        cout << "Enter the elements of the array: \n";

        // For loop execution  
        // i start at 0. as long as i < Number. i++ 
        for (int i = 0; i < Number; i++)
        {
            cout << "array element " << i << ":";
            cin >> array[i];
        }

        cout << "\nEven Numbers are : ";

        // For loop execution
        for (int i = 0; i < Number; i++)
        {
            // condition and execution
            if (array[i] % 2 == 0)
            {
                cout << array[i];
                cout << " , ";
            }
        }
        cout << endl;

        cout << "odd Numbers are: ";

        // For loop execution
        for (int i = 0; i < Number; i++)
        {
            // condition and execution
            if (array[i] % 2 != 0)
            {
                cout << array[i];
                cout << " , ";
            }
        }

        cout << endl;
        cout << "-------------------------------------------------";
    }
    else
    {
        cout << "size is invalid" << endl;
    }

    system("pause");
    return 0;
}

我查看了其他一些程序,但无法弄清楚。我是初学者,所以你能帮我解决这个问题。我被要求使用两个布尔变量名称 <<odd count >> 和 <> 并被要求使用两个数组来解决这个问题。一个 <> 和一个 << Odd Arr[]>> 以及我提到的两个布尔值。

标签: c++

解决方案


只需在元素前打印逗号并检查第一个元素:

    bool is_first = true;
    for (int i = 0; i < Number; i++)
    {
        // condition and execution
        if (array[i] % 2 == 0)
        {
            if(!is_first)
            {
                cout << " , ";
            }
            cout << array[i];
            is_first = false;
        } 
    }

推荐阅读