2016-09-29 27 views
1

所以即時通訊嘗試從使用strtok函數迭代通過用戶輸入的字符串獲取二進制數。如果用戶輸入alpha,則輸出0,如果用戶輸入beta,則輸出1.因此,如果用戶輸入「alpha beta alpha alpha alpha」,則輸出應該是「01010」。我有以下的代碼,但我不知道哪裏會出錯,因爲它沒有做我描述的行爲如何使用strtok打印二進制數字?

#include <math.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <stdint.h> 

#include <string.h> 
int main(int argc, char * argv[]) 
{ 
    char userinput[250]; 
    long binaryarray[250]; 
    char *token; 
    int counter = 0; 
    long binarynumber = 0 ; 
    printf("enter alpha or beta"); 
    scanf("%s", userinput); 
    token = strtok(userinput, " "); 
    while (token != NULL) 
    { 
     if(!strcmp(token, "alpha")) 
     { 
      binaryarray[counter] = 0; 
      counter += 1; 
     } 
     if(!strcmp(token, "beta")) 
     { 
      binaryarray[counter] = 1; 
      counter += 1; 
     } 
     token = strtok(NULL, " \0"); 
    } 
    for(int i = 0; i < counter; i++) 
    { 
     binarynumber = 10 * binarynumber + binaryarray[i]; 
    } 
    printf("%ld", binarynumber); 
} 

我該如何解決這個問題?

+0

好吧,我剛剛發佈的實際代碼 – h101

回答

0

正如已經@SouravGhosh說,你應該使用fgets以存儲用戶使用空格插入整個字符串。

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

int main(int argc, char * argv[]) 
{ 
    char userinput[250] = {0}; 
    char binaryarray[250]; 
    char* token; 
    size_t counter = 0; 

    printf("enter alpha or beta"); 
    fgets(userinput, sizeof(userinput), stdin); 

    token = strtok(userinput, " \n\0"); 

    while ((token != NULL) && (count < sizeof(binaryarray))) 
    { 
     if(!strcmp(token,"alpha")) 
     { 
      binaryarray[counter] = '0'; 
      counter++; 
     } 
     else if(!strcmp(token,"beta")) 
     { 
      binaryarray[counter] = '1'; 
      counter++; 
     } 
     token = strtok(NULL, " \n\0"); 
    } 

    for(size_t i=0 ; i< counter; i++) 
    { 
     printf("%c", binaryarray[i]); 
    } 

    printf("\n"); 
} 

但是你有其他問題:

  1. 您的令牌應該" \n\0"匹配詞與詞之間的所有可能的字符。
  2. 所有標記必須用一個單一的輸入的情況下,第一strok進行檢查,因此使用沒有空格
  3. 一個int來計算你的「二進制」,並與"%ld"格式說明打印不打印前導零。您可以直接將字符存儲到緩衝區中。
+0

也因此如何將我修改代碼,使其始終打印第1的二進制數,無論α或β是否被調用。因此,例如alpha beta將在二進制101和beta beta alpha將是1110 – h101

+0

char binaryarray [250] = {'1'}; int counter = 1; – LPs

+0

有沒有電子郵件我可以通過問你一個問題?由於某種原因,我有一些問題,因爲學術政策,我不允許發佈我的所有代碼。 – h101

2

的問題是,對於

scanf("%s",userinput); 

掃描在遇到第一個空白後停止。因此,它不能掃描並存儲的輸入像

α,βα,β的α

由空格隔開。引用C11,章§7.21.6.2

s

匹配的非空白字符的序列。

可能的解決方案:您需要使用fgets()讀取與空格的用戶輸入。

+0

而前導零不會被打印出來。最好是構造一個「0」和「1」字符串,而不是將其轉換爲看起來像二進制數的小數。 –

+0

或者直接打印數字,而不是將它們存儲起來以便在最後一次打印。 –

+0

@JohnBollinger所以我只是嘗試了STRCMP功能後,將打印報表的仍然只是打印出1位 – h101

相關問題