2016-12-26 62 views
-2

我有一個structs的數組,其中填充了一些值。我提示用戶輸入一個值。然後我需要檢查數組以查看用戶輸入的值是否包含在數組中。
如果找到了,那麼程序將繼續執行。
如果找不到,程序會提示用戶輸入不同的值。如何在一個while循環的條件下與多個值進行比較

下面是我已經寫的代碼。你可以看到我試圖掃描數組作爲do-while循環條件的一部分,但這不起作用。

do 
{ 
    printf("Insert the number you want to search:\n"); 
    numero = getInputFromUser(); 
} while (for (i = 0; i < numAlunos; i++) // This is where I need help 
      numero != vAlunos[i].numero) 

我該如何掃描一個數組作爲循環條件的一部分?

+2

寫,將執行第一個新功能搜索並返回它是否被發現。然後可以在while循環條件中使用該函數。 – pstrjds

+0

我試圖重新引用您的問題並清理那裏的代碼,以便將其專注於您提到的問題。如果我沒有正確清理它,請隨時進一步編輯它或展開我所做的。 – pstrjds

回答

2

如果您使用的是C99,那麼您可以訪問stdbool.h,並且可以使用布爾類型,如果不是,只需根據您使用的替代方法(如typedef,#define或只需用int返回0和1即可。

我也假設你的數組結構和數組長度變量是全局的,但如果它們不是,你可以修改這個函數來傳遞它們作爲參數。

bool checkForValue(int numeroToSearch) // Guessing int, but change as needed 
{ 
    int i; 
    for (i = 0; i < numAlunos; i++) 
    { 
     if(numeroToSearch == vAlunos[i].numero) 
     { 
      return true; 
     } 
    } 
    return false; 
} 

那麼你應該能夠使用這樣的:

do 
{ 
    printf("Insert the number you want to search:\n"); 
    number= validar_insert (2150001, 2169999);//check if the input is between this values 

    printf("That number doeste exist.\n"); 
    printf("Enter another number.\n"); 
}while (!checkForValue(numero)) 
+0

除了事物之外,我得到了你所說的全部內容:如何獲得「numeroToSearch」以便在checkForValue函數中使用它?我將不得不從使用循環的函數中返回它,對吧?我 –

+0

@NelsonSilva - 你把它傳遞給函數。如果你看看我發佈的do-while循環代碼,你會發現我正在傳遞'numero'。我在函數中調用了'numeroToSearch'來明確它是什麼。我添加的do-while循環是直接從您的示例代碼中獲取的,我所做的唯一的事情就是將您已經在do-while的條件中列出的for循環移到一個函數中,然後我從做的時候。 – pstrjds

1

如果你不介意使用編譯器擴展,GCC和鏘提供statement-expressions可嵌入的條件內:

do { 
    printf("Insert the number you want to search:\n"); 
    numero = getInputFromUser(); 
} while (({ 
    int i = 0; 

    while(i < numAlunos && vAlunos[i] != numero) 
     ++i; 

    i == numAlunos; // "return value" of the statement-expressions 
})); 

See it live on Coliru

相關問題