C 中的字符验证

标签 c

我在程序中遇到字符验证问题。程序因 isalpha() 的使用方式而失败。更准确地说,如果您输入字母字符而不是数字,则会进入无限循环...请帮忙。

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

#define TAB_SPACE_SIZE 8

int replaceTab(int numberOfTabs)
{
    int x;
    for (x = 0; x < numberOfTabs; x++)
    {
        char tabSpace[TAB_SPACE_SIZE];
        char space = ' ';
        int i;
          for (i = 0; i < 8; i++)
          {    
               tabSpace[i] = space;
               printf("%c", space);
          }
    }
}

int checkInput()
{
    int numberOfTabs;
    char response;
    char enter;
    printf("How many tabs am I to convert to spaces and print the output? ");
    scanf("%d", &numberOfTabs);
    if (numberOfTabs > 0)
    {
       replaceTab(numberOfTabs);
       system("pause");
       scanf("%c", &enter);
       printf("\nTry again? Yes(Y)/No(N)? ");
       scanf("%c", &response);
       printf("\n");
       switch (response)
       {
           case 'Y': checkInput();
                     break;
           case 'N': exit(0);
                     break;
           default: printf("\nEnter either Y or N.");
                    break;
       }
    }   
    else if (numberOfTabs == 0)
    {
       printf("The number of tabs cannot be zero. Press Enter to try again.");
       system("pause");
       checkInput();
    }
    else if isalpha(&numberOfTabs)
    {
       printf("You must enter a number. Press Enter to try again."); 
       system("pause");
       checkInput();
    } 
    else
    {
       printf("The number of tabs has to be a positive number. Press Enter to try again.");    
       system("pause");
       checkInput();                      
    }
    getchar();
    getchar();
}

int main()
{
    while (checkInput());
}

最佳答案

更改输入方案

...并删除错误使用的 isalpha(&numberOfTabs)

for (;;) {
  printf("How many tabs am I to convert to spaces and print the output? ");
  char buf[40];
  if (fgets(buf, sizeof buf, stdin) == NULL) {
    printf("We are done."); 
    return -1;
  }
  if (1 != sscanf(buf, &numberOfTabs)) {
    printf("You must enter a number. Try again."); 
    continue;
  }
  if (numberOfTabs <= 0) {
    printf("The number of tabs has to be a positive number. Try gain.");    
    continue;
  }
  else {
    break;  // I'd put this whole loop in a function and use return here.
  }
}

顺便说一句:在使用 scanf("%c", 的地方,您肯定希望 scanf("%c", 消耗前导空格。

关于C 中的字符验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20692787/

相关文章:

c - 大括号内的变量声明

c - 在 C 中用字符串插入二叉树

c - GNU89,混合声明和循环初始声明

c - 在 if 语句中声明数组

c - 将 C 程序分解为多个文件时,gcc 返回 undefined reference

c - 在 C 编程标准中,整数 "-127-1U"是什么意思?

c - 如何使用 C 语言处理 http 服务器接收到的 <form> 数据,例如 (key=value&key=value&key=value&...) 并将每个值分配给变量?

c - fork() 的目的是什么?

c - 需要帮助找出为什么 for 循环的计数器变量被循环内的函数更改

C 3D 字符数组函数返回字符数组