c - 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
解决方案
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
请注意,函数永远不会调用自己。他们只是运行循环,直到输入有效。
推荐阅读
- asp.net - System.Web.UI.WebControls.FileUpload' 不包含 'HasFiles' 的定义,也没有扩展方法
- jasper-reports - 当里面的底部框架是空白的时,如何缩小框架。?
- ruby-on-rails - 如何在 Ruby on Rails 中实现文章?
- css - 引导按钮和加载动画
- python-3.x - 在 tkinter 上加载图像
- yii2 - 在 yii2 中定义所有用户 (user,guest,admin,..) 的访问角色
- html - 如何从网页中提取超链接地址
- javascript - 如何在 googlechart api 中添加函数 SelectHandler
- docker - 在 docker 中启动 Zabbix Server 会替换配置文件中没有任何内容的字符串 →
- java - 将两个通用记录合并为一个并将其写入镶木地板文件