2012-11-13 54 views
2

我被賦予了這個任務,這是我到目前爲止編寫的代碼。此代碼只接受一個字母時,它應該做的不是字母比較多,所以我可以在一個字類型,這將是在莫爾斯電碼c編程scanf

#include "stdafx.h" 
#include <ctype.h> 
#include <stdlib.h> 
#include <string.h> 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    char input[80], str1[100]; 

    fflush(stdin); 
    printf("Enter a phrase to be translated:\n"); 
    scanf("%c", &input); 
    int j = 0; 
    for (int i = 0; i <= strlen(input); i++) 
    { 
     str1[j] = '\0'; 
     switch(toupper(input[i])) 
     { 
      .................. 
     } 
     j++; 
    } 
    printf("\nMorse is \n %s\n", str1); 
    fflush(stdout); 
    //printf("%s\n ",morse); 
    free(morse); 
} 
+0

@尼古拉:參考:HTTP://meta.stackexchange .com/questions/147100/the-homework-tag-is-now-official-deprecated – Default

+0

您將分配給莫爾斯字符串的小內存!爲什麼不聲明和初始化它作爲一個數組,如'char morse [] =「...」;' –

+0

首先,請標記作業問題。然後,提示 - 通過ASCII碼索引的靜態表,將字符映射到莫爾斯碼字符串。 –

回答

6

你scanf函數具有%c其中預計只有一個字符。使用%s讀取C-字符串:

scanf("%s", input); 

參數來scanf()是指針類型。由於c字符串名稱是指向第一個元素的指針,因此不需要說(&)的地址。

如果您只讀取單個字符,則需要使用&

例如爲:

scanf("%c", &input[i]); // pass the address of ith location of array input. 
+0

您已在您的答案中更正了指針參數,但是明確提及原始類型的錯誤類型會很好。 –

+0

@DanielFischer更新了一個解釋。 –

+1

謝謝,非常好。但我不會unupvote只是重新編輯版本;) –

2

閱讀使用%s%c的字符串。另外一個字符串已經是一個指針了,不需要獲取它的地址。因此,改造這個:

scanf("%c", &input); 

到:

scanf("%s", input); 
2

scanf("%c", &input);將讀取單個字符,你可能尋找scanf("%s", input);

+3

刪除輸入前面的&。 –

+0

的確,快速複製/粘貼錯誤 – emartel