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

Gna*_*Rad 3 c++ iostream input c-strings while-loop

我创建了一个程序来计算提供的字符串中元音的数量.它正确计算元音,并在用户提供"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;

    }

}
Run Code Online (Sandbox Code Playgroud)

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

小智 6

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