程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何让程序循环直到输入字符?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

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

开发过程中遇到如何让程序循环直到输入字符?的问题如何解决?下面主要结合日常开发的经验,给出你关于如何让程序循环直到输入字符?的解决方法建议,希望对你解决如何让程序循环直到输入字符?有所启发或帮助;

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

#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*)会调用未定义的行为@H_772_22@。
  • 条件 result = '%s'(将实现定义的值分配给 result 而不检查其值)看起来很奇怪
  • findi() 调用 @H_392_5@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;
}

大佬总结

以上是大佬教程为你收集整理的如何让程序循环直到输入字符?全部内容,希望文章能够帮你解决如何让程序循环直到输入字符?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: