gpt4 book ai didi

C 中的字符验证

转载 作者:行者123 更新时间:2023-11-30 15:41:04 24 4
gpt4 key购买 nike

我在程序中遇到字符验证问题。程序因 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com