【发布时间】:2018-02-26 10:40:37
【问题描述】:
我有一个程序应该将 char 整数转换为实际整数。它必须与教授编写的 Main 方法兼容。我想我有一个实际转换的解决方案,但我一直在无限循环。我知道我应该返回 Null 但我不知道如何。请问有人可以帮忙吗?这个函数也应该忽略字符字母并在每个字符字母后有一个新的空格。所以 123fgf456 将打印 123(换行符)456。
The function I need help with.
#include <stddef.h>
/*
* Scans inputString, ignoring leading whitespace (spaces, tabs, and newlines)
* to find the first decimal digit, which it interprets as the most significant
* digit of a decimal number, and continues scanning until finding the first
* non-decimal digit. The digits found are converted to an integer, which is
* stored in the location pointed to by integerPtr. This function returns a
* pointer to the first non-digit after the first digit, unless a
* non-whitespace, non-digit is encountered before a digit, in which case,
* NULL is returned and the location pointed to by integerPtr is not changed.
*
* @param integerPtr A pointer to the integer in which to store the integer
* converted from the ASCII string
* @return a pointer to the first non-digit character found if a number was
* successfully converted, NULL if not
*/
char * asciiToInteger(char *inputString, int *integerPtr) {
int i =0; int j=0; int num =0; char terminate;
if(inputString[i] == '\0') return NULL;
if(inputString[i] == ' '){return NULL;}
while(*inputString != '\0')
{
if(*inputString >= '0' && *inputString <= '9')
{
if(inputString[i] == ' '){break;}
num = num *10 + inputString[i]- '0';
*integerPtr = num;
}
inputString++;
}
return inputString;
}
#include <stdio.h>
#include <stddef.h> // for definition of NULL
char * asciiToInteger(char inputString[], int *integerPtr);
int main() {
char inputBuffer[1024];
char *ptr = NULL;
int integer = 8888;
while(fgets(inputBuffer, sizeof(inputBuffer), stdin)) {
ptr = inputBuffer;
int done = 0;
while(!done) {
char *newPtr = asciiToInteger(ptr, &integer);
if(newPtr == NULL) {
if(*ptr != '\0')
++ptr; // Skip over offending character
else
done = 1;
} else {
printf("%d\n", integer);
ptr = newPtr;
}
}
}
return 0;
}
【问题讨论】:
-
asciiToInteger永远不会返回NULL,所以条件newPtr == NULL永远不会发生,所以你永远不会设置done = 1,所以你有一个无限循环。评论“跳过违规字符”似乎与asciiToInteger实际所做的不相符,即它始终贯穿到字符串的末尾,忽略违规字符。 -
感谢您的建议。所以我可以说 if(inputString[i] == '\0')return NULL;那行得通吗?我尝试以多种方式返回 NULL,但发生的情况是我将输入 123,然后我得到并输出 '123',但程序一直要求输入。永无止境。所以我认为我没有正确实现 NULL 。对不起,我是 C 和指针的新手
-
你可以,尽管保留函数原样并将主代码更改为
if ( *newPtr == '\0' ) done = 1;并没有错。那时你不应该对ptr做任何事情,因为它仍然指向字符串的开头。 -
再次感谢您。但是我的教授不希望我们改变主程序。我还不能真正掌握代码(我已经习惯了 Java),但我认为它会遍历一个字符串,直到它遇到一个空终止符?他还告诉我返回一个指向 inputString 的指针,其中一个字母离开了。因此,如果我有 123ef,我会返回一个指向“e”所在位置的指针,但由于我是指针新手,所以我不知道该怎么做。
-
好的。见评论
@return a pointer to the first non-digit character found if a number was successfully converted, NULL if not。您的函数应符合该要求。