我收到了制作字典的任务,该字典最多可包含2个每个单词的定义,该定义必须能够包含空格。
我已经搜索并查看了许多使用获取,fgets,修改"%s"
运算符以包含多个ASCII值的示例。
但问题是,现在它们对我有用,当程序应该获得用户输入时,它似乎只是跳过这一行 - 我在Code Blocks和VS 2012中都尝试过。
这是代码的相关部分,请注意字符串大小temp_word [81], temp_definition [201]
以及words, definitions
为char**
存在限制。
printf("Please enter word no.%d and how many difinitions will it have(1/2):\n", i+1);
scanf("%s %d", temp_word, &no_definitions); //gets word and no. of difinitons
words [i] = (char*) malloc (strlen(temp_word)+1); //memory is allocated according to length of the word, + 1 for \0 that is'n counted by the function
strcpy(words [i] , temp_word);
printf("\n\n%d, %s\n", no_definitions, temp_word); //debugging
printf("Please enter definition no.1:\n");
scanf("%99[^\n]s", temp_definitoin);
definitions_a [i] = (char*) malloc (strlen(temp_definitoin)+1); //memory is allocated according to length of the definition, + 1 for \0 that is'n counted by the function
if (definitions_a [i] == NULL) //must take malloc's failure into account (NULL!)
{
printf ("Memory allocation failed!\n");
goto exit;
}
strcpy(definitions_a [i], temp_definitoin);
if (no_definitions == 1)
{
definitions_b [i] == NULL; //if only one definition is entered the second one will hold the NULL pointer
}
else if (no_definitions == 2)
{
printf("Please enter definition no.2:\n");
gets(temp_definitoin); //gets definition
definitions_b [i] = (char*) malloc (strlen(temp_definitoin)+1); //memory is allocated according to length of the definition, + 1 for \0 that is'n counted by the function
if (definitions_a [i] == NULL) //must take malloc's failure into account (NULL!)
{
printf ("Memory allocation failed!\n");
goto exit;
}
strcpy(definitions_b [i] , temp_definitoin);
}
//}
答案 0 :(得分:1)
BTW scanf("%99[^\n]s", temp_definitoin);
- > scanf(" %99[^\n]", temp_definitoin);
(添加空格,没有s) - chux