inputFile 和outputFile 都需要声明为char 的数组,足以容纳预期的输入1:
#define MAX_FILE_NAME_LENGTH some-value
...
char inputFile[MAX_FILE_NAME_LENGTH+1]; // +1 for string terminator
char outputFile[MAX_FILE_NAME_LENGTH+1];
然后在 scanf 调用中,not 对 inputFile 和 outputFile 使用一元 & 运算符 - 当您将 array 表达式传递为一个参数,它会自动转换为指向数组第一个元素的指针。您还想检查scanf 的结果,以确保您获得了所有输入:
if ( scanf( "%s %s B=%d P=%d", inputFile, outputFile, &numberOfBuffer, &pageSize ) != 4 )
{
// bad input somewhere, probably with numberOfBuffer or pageSize,
// handle as appropriate
}
else
{
// process input normally
}
但是……
scanf 是一个用于进行交互式输入的糟糕工具。很难做到防弹,对于这样的事情,你最好使用fgets或类似的东西将整个内容作为一个大字符串读取,然后从该字符串中提取数据。
可以帮助您简化这一过程的一件事是,您不必在单个 scanf 调用中阅读整行。您可以单独阅读每个元素:
/**
* Start by reading the input file name; we use `fgets` instead
* of `scanf` because it's easier to protect against a buffer overflow
*/
if ( !fgets( inputFile, sizeof inputFile, stdin ) )
{
// error reading input file name, handle as appropriate
}
/**
* Successfully read inputFile, now read outputFile
*/
else if ( !fgets( outputFile, sizeof outputFile, stdin ) )
{
// error reading output file name, handle as appropriate
}
/**
* Now get the number of buffers - the leading blank in the format
* string tells scanf to skip over any leading whitespace, otherwise
* if you have more than one blank between the end of the output file
* name and the 'B' the read will fail.
*/
else if ( scanf( " B=%d", &numberOfBuffer ) != 1 )
{
// error getting number of buffers, handle as appropriate
}
/**
* And finally the page size, with the same leading blank space in the
* format string.
*/
else if ( scanf( " P=%d", &pageSize ) != 1 )
{
// error getting page size, handle as appropriate
}
else
{
// process all inputs normally.
}
- 或者他们的内存需要动态分配,但是当你刚刚学习 C 时,这是以后要解决的问题。