如何在C中添加无限循环?

发布于 2025-01-18 05:15:19 字数 819 浏览 2 评论 0原文

我必须使其成为无限循环,并在输入错误字符时使其返回到开头。该怎么办?

到目前为止,这是我的代码:

#include <stdio.h>
#include <cs50.h>

int main ()
{
// Prompt user for input last choice contender
   char c;
   printf("Last choice: ");
   c = getchar();

      // If last choice is R, loser should play S
    if (c == 'R'|| c == 'r')
    {
        printf("Your next move: S");
    }
// Else if last choice is P, loser should play R
    else if (c == 'P' || c == 'p')
    {
        printf("Your next move: R");
    }
// Else if last choice is S, loser should play P
    else if (c == 'S' || c == 's')
    {
        printf("Your next move: P");
    }
// TO DO: If another character start over
    else if (c != 'S'|| c != 's' || c != 'P' || c != 'p' || c != 'R'|| c != 'r')
}
// TODO: make an infinite loop / start over

I have to make this an infinite loop and also make it go back to the start when a wrong character is an input. What to do?

This is my code so far:

#include <stdio.h>
#include <cs50.h>

int main ()
{
// Prompt user for input last choice contender
   char c;
   printf("Last choice: ");
   c = getchar();

      // If last choice is R, loser should play S
    if (c == 'R'|| c == 'r')
    {
        printf("Your next move: S");
    }
// Else if last choice is P, loser should play R
    else if (c == 'P' || c == 'p')
    {
        printf("Your next move: R");
    }
// Else if last choice is S, loser should play P
    else if (c == 'S' || c == 's')
    {
        printf("Your next move: P");
    }
// TO DO: If another character start over
    else if (c != 'S'|| c != 's' || c != 'P' || c != 'p' || c != 'R'|| c != 'r')
}
// TODO: make an infinite loop / start over

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烧了回忆取暖 2025-01-25 05:15:19

如果我确实正确理解了您的需求,您可以这样做:

#include <stdio.h>
#include <cs50.h>

int main ()
{
    while(true) // or while(1) if you don't want to include stddef or any other lib containing true and false declaration
    // Prompt user for input last choice contender
    {
        char c;
        printf("Last choice: ");
        c = getchar();

        // If last choice is R, loser should play S
        if (c == 'R'|| c == 'r')
        {
            printf("Your next move: S");
        }
        // Else if last choice is P, loser should play R
        else if (c == 'P' || c == 'p')
        {
            printf("Your next move: R");
        }
        // Else if last choice is S, loser should play P
        else if (c == 'S' || c == 's')
        {
            printf("Your next move: P");
        }
        // TO DO: If another character start over
        else if (c != 'S'|| c != 's' || c != 'P' || c != 'p' || c != 'R'|| c != 'r')
    }
}

另外,如果没有满足授权字符,您不需要做任何其他事情就可以在循环开始时重新启动代码。您甚至不需要用最新的 else if 子句捕获它们,因为无论如何到达循环中代码的末尾,一旦到达那里就不会再做任何事情。
(否则 if (c != 'S'|| c != 's' || c != 'P' || c != 'p' || c != 'R'|| c != 'r' ))
但是,如果您希望保留空(无子 {})else if 子句,则应该添加一个 ;在子句的末尾,否则我不知道你当前的代码将如何编译。

我欢迎您使用 stack Overflow,但我建议您遵循一些关于 c 语言的基本指南,看起来您缺少一些严重的基础,这将继续阻碍您当前的学习道路。总的来说,我鼓励您继续学习:)祝您好运!

If I do understand correctly your need, you can do like that :

#include <stdio.h>
#include <cs50.h>

int main ()
{
    while(true) // or while(1) if you don't want to include stddef or any other lib containing true and false declaration
    // Prompt user for input last choice contender
    {
        char c;
        printf("Last choice: ");
        c = getchar();

        // If last choice is R, loser should play S
        if (c == 'R'|| c == 'r')
        {
            printf("Your next move: S");
        }
        // Else if last choice is P, loser should play R
        else if (c == 'P' || c == 'p')
        {
            printf("Your next move: R");
        }
        // Else if last choice is S, loser should play P
        else if (c == 'S' || c == 's')
        {
            printf("Your next move: P");
        }
        // TO DO: If another character start over
        else if (c != 'S'|| c != 's' || c != 'P' || c != 'p' || c != 'R'|| c != 'r')
    }
}

Also, you don't need to do anything else for your code to restart at the beginning of the loop if no authorised character have been met. You don't even need to catch them with your latest else if clause, since, arriving at the end of code in the loop anyway, nothing more will be done once arrived there.
(else if (c != 'S'|| c != 's' || c != 'P' || c != 'p' || c != 'R'|| c != 'r'))
But, if you wish to keep your empty (no sub {}) else if clause, you should add a ; at the end of the clause, or else I don't know how you current code would compile.

I welcome you to stack overflow, but I advise you to follow some basic guide on c language, it looks like you are missing some serious basis that will keep blocking you on your current learning road. Overall, I encourage you to pursue your learning :) Good luck !

暖伴 2025-01-25 05:15:19

我有多种方法可以做到这一点,我推荐使用 while 循环。

添加一段时间(){

}
围绕您想要重申的所有代码,在 while() 参数内您可以有一个像这样的布尔值
布尔值赢=假,
而(!赢了)
当玩家获胜或您不希望玩家继续游戏时添加 won = true !
但我也建议阅读有关 while 循环的内容,谷歌 while 循环 in google

I there are multiple ways of doing this, i recommend a while loop.

Add a while(){

}
around all the code you want to reiterate, inside the while() parameters you can have a boolean like this
boolean won = false,
while(!won)
and add the won = true when a player has won, or when you dont want the player to continue your game!
But i also recommend reading about the while loop, google while loop in google

撩发小公举 2025-01-25 05:15:19

您可以使用无限循环(例如 for(;;)while(1)),它将永远运行,直到出现显式 break 语句遇到。您可以在确定输入有效后使用 break 语句。在那之前,循环将永远运行。

在这种情况下,您可以简单地使用 switch 语句,而不是使用长链 if...else if使用函数 toupper

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main ()
{
    for (;;) //infinite loop
    {
        //NOTE: The following variable must be an "int" in order to
        //be able to distinguish EOF from an actual character.
        int c;

        printf("Last choice: ");
        c = getchar();

        switch ( toupper( c ) )
        {
            case 'R':
                printf( "Your next move: S" );
                break;
            case 'P':
                printf( "Your next move: R" );
                break;
            case 'S':
                printf( "Your next move: P" );
                break;
            case EOF:
                fprintf( stderr, "unexpected error!\n" );
                exit( EXIT_FAILURE );
            default:
                printf( "Input was not ok, please try again.\n" );
                continue;
        }

        //input was ok, so we can break out of the infinite loop
        break;
    }
}

然而,这个程序还不能正常工作:

Last choice: q
Input was not ok, please try again.
Last choice: Input was not ok, please try again.
Last choice: 
Last choice: This is a test.
Input was not ok, please try again.
Last choice: Input was not ok, please try again.
Last choice: Input was not ok, please try again.
Last choice: Your next move: P

正如你所看到的,程序对于同一行输入多次打印错误消息。这是因为 getchar 将返回该行中的每个字符,包括行末尾的换行符,并且每个字符都将被单独处理,直到找到所需的字符之一。这不是你想要的。由于用户输入是基于行的,因此一次读取一整行输入并拒绝整行输入(如果它包含多个字符(除了换行符之外))会更有意义。为了读取整行输入,我建议使用函数 fgets< /code>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main ()
{
    for (;;) //infinite loop
    {
        //need space for 1 character, the newline character and
        //the terminating null character
        char line[3];

        printf("Last choice: ");

        //attempt to read one line of input
        if ( fgets( line, sizeof line, stdin ) == NULL )
        {
            fprintf( stderr, "Input error!\n" );
            exit( EXIT_FAILURE );
        }

        //make sure that line was not too long
        if ( strchr( line, '\n' ) == NULL )
        {
            int c;

            printf( "Please only enter a single character!\n" );

            //discard remainder of line
            do
            {
                c = getchar();

                if ( c == EOF )
                {
                    fprintf( stderr, "Input error!\n" );
                    exit( EXIT_FAILURE );
                }

            } while ( c != '\n' );

            continue;
        }

        switch ( toupper( (unsigned char)line[0] ) )
        {
            case 'R':
                printf( "Your next move: S" );
                break;
            case 'P':
                printf( "Your next move: R" );
                break;
            case 'S':
                printf( "Your next move: P" );
                break;
            default:
                printf( "Input was not ok, please try again.\n" );
                continue;
        }

        //input was ok, so we can break out of the infinite loop
        break;
    }
}

现在程序可以正常运行了:

Last choice: This is a test.
Please only enter a single character!
Last choice: q
Input was not ok, please try again.
Last choice: s
Your next move: P

You can use an infinite loop (e.g. for(;;) or while(1)) which will run forever, until an explicit break statement is encountered. You can use the break statement after determining that the input is valid. Until then, the loop will run forever.

Instead of using a long chain of if...else if, in this case, you can simply use a switch statement, after making the letter upper-case using the function toupper.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main ()
{
    for (;;) //infinite loop
    {
        //NOTE: The following variable must be an "int" in order to
        //be able to distinguish EOF from an actual character.
        int c;

        printf("Last choice: ");
        c = getchar();

        switch ( toupper( c ) )
        {
            case 'R':
                printf( "Your next move: S" );
                break;
            case 'P':
                printf( "Your next move: R" );
                break;
            case 'S':
                printf( "Your next move: P" );
                break;
            case EOF:
                fprintf( stderr, "unexpected error!\n" );
                exit( EXIT_FAILURE );
            default:
                printf( "Input was not ok, please try again.\n" );
                continue;
        }

        //input was ok, so we can break out of the infinite loop
        break;
    }
}

However, this program does not yet work properly:

Last choice: q
Input was not ok, please try again.
Last choice: Input was not ok, please try again.
Last choice: 
Last choice: This is a test.
Input was not ok, please try again.
Last choice: Input was not ok, please try again.
Last choice: Input was not ok, please try again.
Last choice: Your next move: P

As you can see, the program prints the error message several times for the same line of input. This is because getchar will return every character on the line, including the newline character at the end of the line, and every character will be processed individually, until it finds one of the desired characters. This is not what you want. Since user input is line-based, it would make more sense to read a whole line of input at once, and reject the whole line of input if it contains more than one character (in addition to the newline character). In order to read a whole line of input, I recommend using the function fgets:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main ()
{
    for (;;) //infinite loop
    {
        //need space for 1 character, the newline character and
        //the terminating null character
        char line[3];

        printf("Last choice: ");

        //attempt to read one line of input
        if ( fgets( line, sizeof line, stdin ) == NULL )
        {
            fprintf( stderr, "Input error!\n" );
            exit( EXIT_FAILURE );
        }

        //make sure that line was not too long
        if ( strchr( line, '\n' ) == NULL )
        {
            int c;

            printf( "Please only enter a single character!\n" );

            //discard remainder of line
            do
            {
                c = getchar();

                if ( c == EOF )
                {
                    fprintf( stderr, "Input error!\n" );
                    exit( EXIT_FAILURE );
                }

            } while ( c != '\n' );

            continue;
        }

        switch ( toupper( (unsigned char)line[0] ) )
        {
            case 'R':
                printf( "Your next move: S" );
                break;
            case 'P':
                printf( "Your next move: R" );
                break;
            case 'S':
                printf( "Your next move: P" );
                break;
            default:
                printf( "Input was not ok, please try again.\n" );
                continue;
        }

        //input was ok, so we can break out of the infinite loop
        break;
    }
}

Now the program works properly:

Last choice: This is a test.
Please only enter a single character!
Last choice: q
Input was not ok, please try again.
Last choice: s
Your next move: P
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文