簡體   English   中英

使用 scanf 和 printf 使程序無限循環,但通過替換為 cin 和 cout 工作正常

[英]using scanf and printf makes the program infinite loop but by replacing with cin and cout works ok

我的問題是在用戶輸入測試值 0 之前進行輸入,問題只能通過 c 語言解決,我下面的代碼通過使用scanfprintf變成無限循環,但是如果用C++編寫相同的代碼,它可以正常工作,沒有問題,你能幫我完成我缺少的 C 程序嗎?

#include <stdio.h>
#include <stdlib.h>
int main() {
    int click,test=1,count=0;
    char vote;
    scanf("%d",&test);
    while(test){
      int i=0;
      for(int i=0;i<test;i++){
      scanf("%c",&vote);
      scanf("%d",&click);
       printf("%c %d hi \n",vote,click);
}
      scanf("%d",&test);
    }
  //printf("%d\n",count);
    return 0;
}
my test case was
    2
    P 1
    P 2
    2
    P 2
    M -2
    0

在 c++ 中,我的輸出與測試用例完全一樣,但在 c 語言中,它的TLE 或輸出限制超過

在處理 C 時,您應該始終檢查運行時函數的返回值,這是避免出現類似錯誤的最佳方法。

scanf 返回它設法解析的項目數,如果失敗則返回 0。

我個人更喜歡使用 fgets() 從標准輸入讀取,然后使用 sscanf 來解析緩沖區,這樣你就可以(恕我直言)更好地控制進入程序的內容,而不是模糊的 scanf 格式。 使用 scanf 很容易出錯,因為人們往往會忘記所有輸入都已緩沖,而 scanf 從該緩沖區讀取。

例如(僅限目鏡編譯)

int click = 0;
int test = 0;
char buffer[128];
char vote = 0;

do
{
  if ( fgets(buffer,sizeof(buffer),stdin) != NULL)
  {
    // read number of tests
    if (sscanf(buffer, "%d", &test) == 1)
    {
      for(int i=0; i < test; ++i)
      {
        if (fgets(buffer, sizeof(buffer), stdin) != NULL)
        {
          if (sscanf( buffer, "%c %d", &vote, &click) == 2)
          {
            printf( "%c %d hi \n", vote, click );
          }
          else
          {
            fprintf(stderr, "Invalid format encountered\n");
          }
        }
      }
    }
  }
}
while (test);

%c 轉換說明符對前導空格造成問題,因為它不會自動跳過它們。 由於您在循環中接收輸入,因此緩解它的一種方法是在%c之前放置額外的空間。

scanf(" %c", &vote);

暫無
暫無

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

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