问题scanf函数和与fgets [英] Problem with scanf and fgets
问题描述
这是一个家庭作业的一些特定字符串进行排序。我提示字符串数量的用户,他们希望与 scanf函数
来排序,根据这个数字分配一个数组,然后获取字符串本身与与fgets
。
This is for a homework assignment to sort some given strings. I'm prompting the user for the number of strings they'd like to sort with scanf
, allocating an array based on that number, and then getting the strings themselves with fgets
.
一切工作正常,如果字符串的数量是很难codeD,但 scanf函数
的除了让用户决定螺丝的东西了。这里的code:
Everything works fine if the number of strings is hardcoded, but the addition of scanf
to let the user decide screws things up. Here's the code:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#define LENGTH 20 // Maximum string length.
int main(void)
{
int index, numStrings = 0;
char **stringArray;
printf("Input the number of strings that you'd like to sort: ");
assert(scanf("%d", &numStrings) == 1);
stringArray = (char **)malloc(numStrings * sizeof(char *));
for (index = 0; index < numStrings; index++)
{
stringArray[index] = (char *)malloc(LENGTH * sizeof(char));
assert(stringArray[index] != NULL);
printf("Input string: ");
assert(fgets(stringArray[index], LENGTH, stdin) != NULL);
}
// Sort strings, free allocated memory.
return 0;
}
和这里的控制台的样子:
And here's what the console looks like:
Input the number of strings that you'd like to sort: 3
Input string: Input string: foo
Input string: bar
有跳过循环的第一次迭代,从而在所述阵列的开头空字符串。我的问题是,为什么会这样,我怎么能解决这个问题?
It skips over the first iteration of the loop, resulting in an empty string at the beginning of the array. My question is, why does it do that, and how can I fix it?
下面就是控制台看上去与格式字符串%d个\\ N
传递给 scanf函数
:
Here's what the console looks with the format string "%d\n"
passed to scanf
:
Input the number of strings that you'd like to sort: 3
foo
Input string: Input string: bar
Input string: baz
所以,我可以输入所有的字符串,而是一个字符串的第一个提示是在错误的地方。
So, I can input all of the strings, but the first prompt for a string is in the wrong place.
推荐答案
真正的答案(愚见,但不断所谓正确的舆论:P)是不使用 scanf函数
。使用与fgets
来读的第一行(即号码),然后自己分析该字符串,比如的sscanf
或 strtoul将
。这样,你有当有人确实在一个不错的格式不输入数据处理错误的能力,你不必砍周围 scanf函数
的缺乏强劲空白的处理。
The real answer (in my humble but ever-so-correct opinion :P) is not to use scanf
. Use fgets
to read the first line (i.e. the number) and then parse that string yourself with, say, sscanf
or strtoul
. That way you have the ability to handle errors when someone doesn't input the data in a nice format, and you don't have to hack around scanf
's lack of robust whitespace handling.
另外,除非你希望有很多的阵列与-4长度从未使用过的 INT
存储大小。该标准规定了无符号类型为size_t
为无符号类型,它大到足以存储对象的大小和数组索引。使用任何其他类型并不保证工作。
Also, never used an int
to store sizes unless you expect to have a lot of arrays with -4 length. The standard specifies the unsigned type size_t
as an unsigned type that is large enough to store object sizes and array indices. Using any other type isn't guaranteed to work.
这篇关于问题scanf函数和与fgets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!