[英]Getting a string with white-space from user
我收到一份分配字典的作业,每个字典最多可包含2个定义,该定义必须能够包含空格。
我已经搜索并看到了许多使用gets,fgets,修改"%s"
运算符以包括几个ASCII值的示例。
但是问题在于,现在它们对我有用了,当程序应该获得用户输入时,似乎只是跳过了这一行-我在VS 2012的Code Blocks中都尝试过。这是代码的相关部分,请注意,字符串大小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);
}
//}
BTW scanf("%99[^\\n]s", temp_definitoin);
-> scanf(" %99[^\\n]", temp_definitoin);
(添加空格,不加s)– chux
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.