我正在尝试完成一个练习,该练习将有助于巩固我对指针和结构的了解,其中结构指针作为参数传递给函数。所提供的解决方案使用scanf
来获得用户输入,效果非常好,但由于此功能(方法?(被认为是不安全的,我正试图找到实现相同结果的替代方法。
问题是,一个类型为float的结构成员导致了分段错误,其中我将通过结合使用strtof()
和fgets()
将用户输入从char
转换为float
。我之前看过一些我认为可能有用的字符串函数(atof()
和atoi()
-将此函数的返回值转换为float(,但无法成功实现这些函数的转换。正如我所提到的,我正在尝试使用strtof()
,但同样,我没有成功。
这里有一个问题的例子:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
struct Stock {
float cost;
};
#define SIZE 50
void ReadIn(struct Stock *purchase);
void PrintOut(struct Stock *receipt);
int main ()
{
// instantiate struct type
struct Stock product;
// instantiate struct type pointer
struct Stock *pItem;
pItem = &product;
if (pItem == NULL)
{
exit(-1);
}
else
{
ReadIn(pItem);
PrintOut(pItem);
}
return 0;
}
//---- Function Definitions ----//
// read function
void ReadIn(struct Stock *purchase)
{
char pNum[] = {0};
char *pEnd;
printf("nEnter the price: ");
fgets(pNum, SIZE, stdin);
pEnd = (char *) malloc(SIZE * sizeof(char));
purchase->cost = strtof(pNum, &pEnd);
}
// print function
void PrintOut(struct Stock *receipt)
{
printf("nPrice: %.2fn", receipt->cost);
}
我知道我的实现中存在错误,但我不知道如何解决它们。我使用了各种调试技术(printf、IDE内置调试器、lldb(,但我发现结果即使不是不可能,也很难解释。我很感激你的帮助。
char pNum[] = {0};
将pNum
定义为具有单个元素的数组。它只能是一个空字符串(只包含null终止符(。试图存储超过该单个元素将超出界限,并导致未定义的行为
如果您想在该数组中存储多达SIZE - 1
个字符,则需要将其设为SIZE
大:
char pNum[SIZE]; // Initialization is not needed, will be filled in by fgets
您也误解了strtof
的工作原理。您不应该为作为第二个参数传递的指针分配内存。现在的情况是,这是一种通过向变量传递指针来模拟按引用传递的方法。
无论如何,传递一个空指针是可以的:
purchase->cost = strtof(pNum, NULL);
这是一个问题:
char pNum[] = {0};
您已经声明pNum
只存储一(1(个字符,它不能存储SIZE
个字符。任何时候你试图读取它,你都会有缓冲区溢出。您需要将其声明为
char pNum[SIZE+1] = {0}; // +1 for the string terminator
其次,您不应该为pEnd
分配任何内存。strtof
只需将其设置为指向pNum
中第一个而不是转换为float
的字符。您应该检查pEnd
以确保它是一个空白字符——这样您就知道用户输入了一个有效的浮点字符串。
以下是如何进行验证的示例:
void ReadIn(struct Stock *purchase)
{
char pNum[SIZE+1] = {0};
int done = 0;
float tmp;
do
{
printf("nEnter the price: ");
if ( fgets(pNum, sizeof pNum, stdin) )
{
/**
* Do not update your target variable until after you've
* validated the input. pEnd will point to the first
* character in pNum that is *not* part of a valid floating
* point string.
*/
tmp = strtof( pNum, &pEnd );
/**
* isspace returns true/false - we'll assign the result to done
* to control our do/while loop. Basically, as long as the user
* does not enter a valid floating-point value, we'll continue the
* loop.
*/
if ( !(done = isspace( *pEnd )) )
{
/**
* If pEnd doesn't point to a whitespace character, then
* the input is invalid. Write an error message
* and get them to try again.
*/
fprintf( stderr, "%s is not a valid input - try again!n", pNum );
/**
* If there's no newline in pNum, then the user entered
* a string that was too long for the buffer - read any
* remaining characters from the input stream until we see
* a newline.
*/
if ( !strchr( pNum, 'n' ) )
while ( getchar() != 'n' )
; // empty loop
}
}
else
{
/**
* There was a read error on the input stream - while there may be
* ways to recover, for the sake of this example we'll treat it
* as a fatal error and exit the program completely.
*/
fprintf( stderr, "Input error while reading stdin - bailing out...n" );
exit(0);
}
} while ( !done );
/**
* NOW we've made sure our input is valid, so we can assign it to the
* target variable.
*/
purchase->cost = tmp;
}