首页 > 解决方案 > Can't get while loop to work 2 times? (C)

问题描述

So I'm trying to loop the name asking section as well as the age one, the age one worked fine but when I tried to do it with name one it doesn't work. What I'm just trying to achieve is that when you put a number in the name section or vice versa, you get an error message and it loops you back to the same question

 #include <stdio.h>

int vek;
char name[20];
int result1;
int result2;

int main()
{
    FindName();
void FindName() { // it wants me to put a ";" which doesn't make sense to me and doesn't work
    printf("Napis svoje meno \n");
    result2 = scanf("%s",&name);
    while (gethar() != '\n');
    if(result2 == 1){
         printf("Ahoj %s \n",name);
         break;
         system("pause");
    }
    else {
         printf("nepis sem cisla ty kokot \n");
         }
    
    findAge();
} 

void findAge() {
    printf("Napis svoj vek \n");
    result1 = scanf("%d",&vek);

    while (getchar() != '\n');
    if(result1 == 1){
        printf("%s si krasny %d rocny priklad downoveho syndromu  \n ",&name,vek);
    }
    else {
        printf("co si jebnuty \n");
        findAge();
    } 
}

I've tried to just break the loop if it's the right answer but that wouldn't work either, I'm just a beginner

标签: cloopswhile-loop

解决方案


while只要条件为真,循环就会运行主体内的所有内容。您需要将需要重复的代码放在一个块中,介于{和之间}。你在它后面加了一个分号。这意味着一个空语句,或者什么都不做。这样,条件就会被检查,直到它不再为真,但不做任何其他事情。例如:

int i=0;
while(i < 3) {
    printf("%d\n", i);
    i++;
}

这将打印数字 0,1 和 2。然后它停止,因为条件不再为真。

您希望程序看起来像这样。在伪代码中:

main:
    call findName
    call findAge

findName:
    print "Something Eastern European asking for a name"
    result = 0;
    while result != 1:
        result = read input
        if result == 0
            print "Try again"

同样的findAge

请注意,函数永远不会调用自己。他们只是运行循环,直到输入有效。


推荐阅读