2015-11-28 80 views
0

我想寫一個程序來處理用戶在C中的輸入。我必須確保程序接受用戶的輸入,例如在我的程序中將「y」,「是」,「是」作爲「是」以後使用(即需要使用strcmp(xx,「是」)== 0)。我處理了混合大小寫字符。C - 如何照顧C程序中的敏感輸入?

那麼我該怎麼寫一個函數來總結「y」,「yeah」,「yep」,並且畢竟使它們等於「yes」?

IF((STRCMP(字母 「Y」)== 0)|| ......)

return "yes"; 

....... 

另外,如果該程序要求用戶輸入一個問題出於某種目的,如果用戶忘記添加問號,是否可以爲用戶添加問號(?)?

+0

是否足夠好,它帶有Y開頭或它必須是你列出的單詞? –

回答

0

有一個名爲strncasecmp函數,而不是存在於所有系統(我是一個Linux用戶),因爲不是標準功能:

int strncasecmp(const char *s1, const char *s2, size_t n); 

功能看起來是這樣的,如果不存在在你的系統:

int strncasecmp(char *s1, char *s2, size_t n){ 
    if (n == 0){ 
     return 0; 
    } 

    while (n-- != 0 && tolower(*s1) == tolower(*s2)){ 
     if (n == 0 || *s1 == '\0' || *s2 == '\0'){ 
      break; 
     } 
     s1++; 
     s2++; 
    } 

    return tolower(*(unsigned char *) s1) - tolower(*(unsigned char *) s2); 
} 

,你可以使用它像這樣:

#include <stdio.h> 
#include <strings.h> 

int main(void){ 
    char *user_input = "yes"; 
    char *ch = "Y"; 

    if (strncasecmp(user_input, ch, 1) == 0){ 
     printf("True\n"); 
    }else{ 
     printf("False\n"); 
    } 

    return 0; 
} 

正如你可以看到有與區分大小寫沒有問題。該strncasecmp功能在strings.h發現,而不是在string.h


是否有可能增加一個問號(?)的用戶,如果用戶忘記添加一個?

是的,你可以。下面這段代碼是一種方式來幫助你瞭解如何做到這一點:

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

int main(void){ 
    char *question = "What is your Question"; 
    size_t length = strlen(question); 
    char *addQuestion = malloc(length + 2); 

    memcpy(addQuestion,question,length + 1); 
    printf("Before\n%s\n",addQuestion); 

    strcat(addQuestion, "?"); 

    printf("\n"); 
    printf("After\n%s\n",addQuestion); 
    free(addQuestion); 
    return 0; 
} 

輸出:

Before 
What is your Question 

After 
What is your Question? 
+0

*有一個名爲'strncasecmp'的函數* - 該名稱沒有*標準*函數。 –

+0

@KeithThompson你需要'#include '然後你有'strncasecmp](https://www.mkssoftware.com/docs/man3/strncasecmp.3.asp)它在'string.h'中,但是現在你在'strings.h'中找到[檢查這個](http://ideone.com/QZh4XK) – Michi

+0

'我的電腦上不存在'strings.h',我安裝了三個C編譯器。就像Keith Thompson所說的那樣,這個名字沒有**標準的**功能。 –

1

只需比較第一個字母和'y'即可。例如,如果您保存文件名爲user_input在變量用戶輸入「?」

if ((user_input[0] == 'y') || ...) 

至於你的第二個問題,你可以添加選項,例如(它加入之前驗證輸入長度,由於葉片的校正):

if ((input_length > 0) && (user_input[input_length-1] != '?')) { 
    strcat(user_input, "?"); 
}