我正在扫描一个字符串,但我希望该字符串只是整数类型的元素,所以我对此进行了一些验证,它适用于字符,但对于浮点运算而言效果不佳。例如如果我输入1.2值作为输入,那么它就不需要单位输出,而是可以用于2位或更多位。同样,如果我输入12.3,则它不希望输出两位数,而可以输出3位或更多位。谁能告诉我这是怎么回事?有什么办法可以删除在字符串中输入的所有元素,以便仅获得整数值?
P.S。我正在使用字符串,因为我需要根据给定的程序问题从字符串中输入数字。
printf("Enter the number you want to convert into words:\n\n-->");
gets(numberToBeConvertedToWords);
for (i = 0; i != strlen(numberToBeConvertedToWords); i++)
{
while (isdigit(numberToBeConvertedToWords[i]) == 0)
{
// deleting the characters entered in the string.
memset(numberToBeConverted, 0, sizeof(numberToBeConverted));
printf("Please enter positive integers only.\n\n-->");
gets(numberToBeConvertedToWords);
}
}
printf("Entered number: %d", numberToBeConvertedToWords);
convertAndPrintNumberToWords(numberToBeConvertedToWords);
回答书面问题:
如何从C语言的字符串(字符数组)中删除所有数据?
典型的方法是将字符串的每个字符设置为零。最简单的方法是使用memset,假设您知道该字符串有多少有效内存。
//Safe, because we know the length of the string
char s[100];
memset(s, 0, 100);
//Only safe if the string is correctly null-terminated
char* s = getSomeString();
memset(s, 0, strlen(s));
解决隐含的问题:
似乎您实际上要问的问题是“为什么我的代码没有达到我的期望?”。对于堆栈溢出,含糊不清的“帮助我”问题通常是无关紧要的。如果您可以提出有关问题的具体问题,则会得到更好的答复。在这种特定情况下,获得“不正确”输出将很有帮助,因为很难理解意外行为的实际含义。
但是,我猜测您的已编辑代码未达到预期效果的原因是while
位于一个奇怪的地方。如果遇到“。”,则isdigit
将返回0,并且将正确擦除字符串。但是,您将得到一个新的字符串在while循环内,这意味着您从当前位置开始而不是字符串的开始验证新字符串。
您可能想将while循环移到for循环之外:
BOOL valid = true;
do
{
gets(numberToBeConvertedToWords);
// reassigning the bool value as "true" so that loop does not to go infinite
// loop just in case if it's changed from 'if' block.
valid = true;
for (i = 0; i != strlen(numberToBeConvertedToWords); i++)
{
if(!isdigit(numberToBeConvertedToWords[i]))
{
// deleting the characters entered in the string.
memset(numberToBeConverted, 0, sizeof(numberToBeConverted));
printf("Please enter positive integers only.\n\n-->");
valid = false;
//Exit the for loop for this word
break;
}
}
} while(!valid);