簡體   English   中英

從用戶獲取帶有空格的字符串

[英]Getting a string with white-space from user

我收到一份分配字典的作業,每個字典最多可包含2個定義,該定義必須能夠包含空格。

我已經搜索並看到了許多使用gets,fgets,修改"%s"運算符以包括幾個ASCII值的示例。

但是問題在於,現在它們對我有用了,當程序應該獲得用戶輸入時,似乎只是跳過了這一行-我在VS 2012的Code Blocks中都嘗試過。這是代碼的相關部分,請注意,字符串大小temp_word [81], temp_definition [201]以及words, definitionschar**都有限制。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM