微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何让程序循环直到输入字符?

如何解决如何让程序循环直到输入字符?

我真正想要实现的是:你输入你的名字,得到一个像“你的名字是”这样的响应,如果你输入一个数字,你会得到一个像“无效输入”这样的响应,它会让你回到“输入您的姓名部分

#include <stdio.h>
char i[20];
int result;
int main()

{
void findi(); // im trying to loop it back here if a number is entered instead of a character
printf("Enter your name\n");
result = scanf("%s",&i);
while(getchar() != '\n'){ //dont kNow how to make it work without the '!'
    if(result = '%s'){
        printf("Your name is: %s",&i); 
        return 0;
    }
    else{
        printf("Invalid input"); //doesnt work 
        findi();
    }
   }
}
//program just ends after a character is entered instead of continuing 

解决方法

  • &i (char(*)[20]) 用于 %s(期望 char*)会调用未定义的行为
  • 条件 result = '%s'(将实现定义的值分配给 result 而不检查其值)看起来很奇怪。
  • findi() 调用 main()(此处未公开)不一定意味着循环。

试试这个:

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

int main(void)
{
    char i[20];
    printf("Enter your name\n");
    /* an infinite loop (loop until return or break) */
    for (;;) {
        int number_exists = 0,j;
        /* limit length to read and check the result*/
        if (scanf("%19s",i) != 1) {
            printf("read error\n");
            return 1;
        }
        /* check if a number is entered */
        for(j = 0; i[j] != '\0'; j++) {
            if (isdigit((unsigned char)i[j])) {
                number_exists = 1;
                break;
            }
        }
        /* see the result */
        if (number_exists) {
            /* one or more number is entered */
            printf("Invalid input\n");
        } else {
            /* no number is entered : exit from the loop */
            printf("Your name is: %s\n",i); 
            break;
        }
    }
    return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。