簡體   English   中英

在C中使用多個scanf時忽略scanf空間的問題

[英]Issues ignoring spaces with scanf when using multiple scanf's in C

我試圖在一個小程序中多次使用scanf來獲取保證有空格的輸入。 盡管看起來像scanf("%[^\\n]", string);但是從多個線程中瀏覽scanf("%[^\\n]", string); 是使它忽略空格的方法。 這適用於一行,但是該行之后的任何其他scanf都不會通過,並且它們各自的字符串如下:

Action: J���J
 Resolution: J:F�J�B�J

這里有一些示例代碼,我認為可以,但是沒有用。

#include <stdio.h>

int main(void)
{   
    char str1[100];
    char str2[100];

    printf("Situation?\n");
    scanf("%[^\n]", str1);

    printf("Action Taken?\n");
    scanf("%[^\n]", str2);

    printf("Situation: %s\n",str1);
    printf("Action: %s\n",str2);
}

如果在出現提示時輸入“ Just a test”,則會發生以下情況:

Situation?
just a test
Action Taken?
Situation: just a test
Action: ��_��?�J.N=��J�J�d�����J0d���8d��TJ�J

有什么建議或解決方案(不包括fgets )? 對正在發生的事情的解釋也很好。

編輯:在scanf處的解決方案:“%[^ \\ n]”跳過第二個輸入,但“%[^ \\ n]”沒有。 為什么?

加入char* fmt = "%[^\\n]%*c"; 工作了100%。

char* fmt = "%[^\n]%*c";

  printf ("\nEnter str1: ");
  scanf (fmt, str1);
  printf ("\nstr1 = %s", str1);

  printf ("\nEnter str2: ");
  scanf (fmt, str2);
  printf ("\nstr2 = %s", str2);

  printf ("\nEnter str3: ");
  scanf (fmt, str3);
  printf ("\nstr2 = %s", str3);

  printf ("\n");

更改

scanf("%[^\n]", str1);

scanf("%[^\n]%*c", str1);//consume a newline at the end of the line

方法數量:

而不是以下不消耗Enter'\\n' 問題(這是問題所在):

scanf("%[^\n]",str1);
  1. 消耗尾隨的換行符。 "%*1[\\n]"僅消耗1 '\\n' ,但不保存。

     scanf("%99[^\\n]%*1[\\n]" ,str1); 
  2. 在下一個scanf()上使用結尾的換行符。 " "會占用先前的空白和前導空白。

     scanf(" %99[^\\n]", str1); 
  3. 使用fgets() ,但是當然不是scanf() 最好的方法。

     fgets(str1, sizeof str1, stdin); 

無論采用哪種解決方案,都應限制讀取的最大字符數並檢查函數的返回值。

    if (fgets(str1, sizeof str1, stdin) == NULL) Handle_EOForIOError();

對於您的問題,我沒有一個直接的答案,如果您要輸入一行,為什么不簡單地使用fgets (甚至是gets )呢?

解決方案一:使用scanf

如果您仍然想用scanf讀取它,@chux和@BLUEPLXY提供的答案就足夠了。 喜歡:

 scanf(" %[^\n]", str);  //notice a space is in the formatted string

要么

 scanf("%[^\n]%*c", str);

解決方案二:使用getline() (盡管它是POSIX擴展名)

因為有時使用gets()和'fgets()`是不可靠的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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