【问题标题】:Ask to insert numbers in a string array, and repeat the question until the user has entered only numbers. Then make the array an integer "atoi()"要求在字符串数组中插入数字,并重复该问题,直到用户只输入数字。然后使数组成为整数“atoi()”
【发布时间】:2021-07-20 05:06:10
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main()
{
char k[100]; //To input the numbers.

    printf("\nPlease, insert a number:\t");
    fgets(k,20,stdin); //Inserting the numbres

    int y=0;
    int i=0;
    do{//if any character loop.
        if (y!=0)
        {
            printf("\nPlease, insert a number:\t");
            fgets(k,20,stdin);
        }

        while (k[i]!='\n')
        {
            if (isdigit(k[i])==0) y++;
            printf("y=%d", y);
            i++;
        }

    //if (x>0) break;
    }while (y!=0);

    printf("\nk = %s\n",k); //Save key

    int w;
    atoi(k);
    w = atoi(k);
    printf("w = %d",w);
}

/问题在插入字符和进行下一次运行时中继。 //获取用户的完整输入并检查用户是否只输入了数字,然后仅当数组中有任何字符时提示用户再次用数字输入整个字符串。 这个想法只是接受数组中的数字。/

【问题讨论】:

    标签: arrays c string loops fgets


    【解决方案1】:

    现在这行得通,问题是当您输入的数量超过数组可能接受的数量时,它会产生一个奇怪的循环。

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
    int main()
    {
    char k[100]; //To input the characters to code.
    
        int y;
        int i=0;
        do{
            printf("\nPlease, insert a number:\t");
            fgets(k,20,stdin);
            y=0;
    
            i=0;
            while (k[i]!='\n')
            {
                if (isdigit(k[i])==0) y++; //if not a digit.
                printf("y=%d", y);
                i++;
            }
    
            i=0;
            if (y>=1)
            {
                while (k[i]!='\0')
                {
                    k[i]='\0';
                    i++;
                }
            }
    
        //if (x>0) break;
        }while (y!=0);
    
        printf("\nk = %s\n",k); //Save key
    
        int w;
        atoi(k);
        w = atoi(k);
        printf("w = %d",w);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多