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

问题描述 投票:3回答:1

我创建了一个程序来计算提供的字符串中元音的数量。它正确计算元音,并在用户提供“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] != '\0')
        {
            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;

    }

}

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

c++ input while-loop iostream c-strings
1个回答
6
投票

在写入“y”并按下输入按钮后,“Y”和"/n"都存储在输入缓冲区中,因此“y”转到应答字符,“/ n”被认为是下一个获取线的输入。有一些解决方案。您可以在cin.ignore()之后添加对cin >> yes的调用。或者你可以做一个字符串,并在那里使用getline而不是operator>>

© www.soinside.com 2019 - 2024. All rights reserved.