其他分享
首页 > 其他分享> > C While循环不重新分配字符串值

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

作者:互联网

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

    }

}

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

解决方法:

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

标签:c-strings,c,while-loop,input,iostream
来源: https://codeday.me/bug/20190823/1697058.html