C 循环不重新分配字符串值

C++ While loop not re-assigning string value

本文关键字:分配 字符串 循环 新分配      更新时间:2023-10-16

我创建了一个程序,该程序计算提供的字符串中的元音数量。它正确计数元音并在用户提供" Y"或" Y"时重复。但是,当重复重复时,它会自动分配"我试图使用的C弦。

int main()
{
    //Creating repeating decision
    char answer = 'y';
    while ((answer == 'y') || (answer == 'Y'))
    {
        //declaring our C-String
        char ourString[81] = "Default";
        //Prompting user for a string, storing it as a C-String
        std::cout << "Please enter a string!(Less than 80 characters please.)n";
        std::cin.getline(ourString, 81);
        //Using a loop to count the amount of vowels
        int ourNum = 0;
        int vowels = 0;
        while (ourString[ourNum] != '')
        {
            switch (ourString[ourNum]) {
            case 'a':
            case 'A':
            case 'e':
            case 'E':
            case 'i':
            case 'I':
            case 'o':
            case 'O':
            case 'u':
            case 'U':
            case 'y':
            case 'Y':
                vowels++;
                ourNum++;
                break;
            default:
                ourNum++;
                break;
            }
        }
        std::cout << "The numbers of vowels in: "" << ourString << "" is " << vowels << "!n";
        std::cout << "Do again? Please enter "Y" to repeat, or any other character to escape.";
        std::cin >> answer;
    }
}

任何方向都将不胜感激。谢谢!

写作" y y"之后并按下" y y"的输入按钮。"/n"存储在输入缓冲区中,因此" y y"转到答案char,并"/n n&quot"被认为是下一个Getline的输入。有一些解决方案。cin >> yes之后,您可以将呼叫添加到cin.ignore()。或者,您可以制作一个字符串,然后使用getline而不是在那里的operator>>