重复数组C++

repeating array C++

本文关键字:C++ 数组      更新时间:2023-10-16

我有一个问题无法继续我的工作,我的问题是使数组总是重复。这是我的程序

#include <iostream>
#include <windows.h>
#include <conio.h>
using namespace std;
int main()
{
    system("color 0B");
    char huruf[5] = {'a', 'b', 'c', 'd', 'e'}, a;
    int i, x;
    cout << "nnInput a character : ";
    cin >> a;
    for (i = 0 ; i < 5 ; i++)
        if (huruf[i] == a)
            x = 1;
        if (x == 1)
            cout << "THERE IS";
        else
            cout << "THERE IS NO";
}

我希望Input a Character :总是重复自己,这样我就可以多次输入字符。

您需要一个循环在下面的例子中,点击"回车"键可以使脱离循环

    #include <iostream>
    #include <windows.h>
    #include <conio.h>
    using namespace std;
    int main()
    {
        system("color 0B");
        char huruf[5] = {'a', 'b', 'c', 'd', 'e'}, a;
        int i, x;
        do
    {
        x = 0;
        cout << "nnInput a character : ";
        cin >> a;
        for (i = 0 ; i < 5 ; i++)
            if (huruf[i] == a)
                x = 1;
            if (x == 1)
                cout << "THERE IS";
            else
                cout << "THERE IS NO";
    } while (a != 'n');
  }

您的最佳选择可能是使用"while"循环。

所以你可以在你的程序中添加这样的东西:

bool choice = true;
while (choice)
{
    [stuff you want to repeat]
    std::cout << "Do you want to enter another character? Enter 1 for yes or 2 for no." << endl;
    int num;
    cin >> num;
    if (num == 2)
    {
        choice = false;
    }
}

或者,你可以稍微改变一下,让它不那么麻烦:

int main()
{
    system("color 0B");
    char huruf[5] = {'a', 'b', 'c', 'd', 'e'}, a;
    int i, x;
    bool choice = true;
    while (choice)
    {
        cout << "nnInput a character, or -1 to quit: ";
        cin >> a;
        if (a == -1)
        {
            choice = false;
        }
        for (i = 0 ; i < 5 ; i++)
            if (huruf[i] == a)
                x = 1;
            if (x == 1)
                cout << "THERE IS";
            else
                cout << "THERE IS NO";
    }
}