我在程序中遇到字符验证问题。该程序无法使用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());
}
答案 0 :(得分:1)
更改输入方案
...并删除未正确使用的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",
使用前导空格。
答案 1 :(得分:0)
你的其他if语句缺少paransheses,如果你在isalpha函数中得到numberOfTabs的地址,它会比较numberOfTabs 的地址是否为alpha。您可能希望将其更改为:
else if (isalpha(numberOfTabs))
关于下面的评论,您可以更改它,以便在scanf之后检查numberOfTabs是否为alpha:
scanf("%d", &numberOfTabs);
if (numberOfTabs > 0 && !isalpha(numberOfTabs))
{ ...
这样你的replaceTab函数中的循环不会循环x次(取决于你输入的字符)