2015-06-30 102 views
-5

的問題:當輸入爲*,用戶需要重新輸入名稱。有一個最大輸入限制是25個字符,結束輸入輸入鍵。名稱不能顯示

#include <stdio.h> 
#include <conio.h> 
#define MAX 25 
char welcomeMsg[]= "Please enter your name without '*' or # " ; 
char errorMsg[]= "\nError, please re-type your name. "; 

void main(void) 
{ 
int j; 
char input; 
char name[MAX]; 
j=0; 
puts(welcomeMsg); 

do 
{ 
    input = getche(); 
    if(input == '*' || input =='#') 
    { 
     puts(errorMsg); 
     j = 0; 
     continue; 
    } 
    scanf("%s", name[j]); 
    j++; 
} while (j < MAX && input != '\r'); 

name[j] = NULL; 
puts("\nYour name is"); 
puts(name); 
} 
+2

問題是什麼? –

+0

您不必在字符串文字中明確添加'\ 0'。 –

+0

'main'被錯誤地聲明!應該是'int main(int argc,char ** argv)'。 'getche'沒有定義。您應該測試'scanf'的結果(掃描的項目數) –

回答

0

我已經修改了你的代碼。請參考下面

#include <stdio.h> 
#include <conio.h> 
#define MAX 25 
char welcomeMsg[]= "Please enter your name without '*' or # " ; 
char errorMsg[]= "\nError, please re-type your name. "; 

void main(void) 
{ 
    int j; 
    char input; 
    char name[MAX]; 
    j=0; 
    puts(welcomeMsg); 

    do 
    { 
     input = getche(); 
     if(input == '*' || input =='#') 
     { 
      puts(errorMsg); 
      j = 0; 
      continue; 
     } 
     name[j] = input; 
     j++; 
    } while (j < MAX && input != '\r'); 

    name[j] = 0; 
    puts("\nYour name is"); 
    puts(name); 
} 

enter image description here

+0

非常感謝,我學到了很多東西。 – AgentPerry

0
scanf("%s", name[j]); 

是錯誤的,寫

name[j] = input; 

代替。 scanf會讀取整個字符串,格式字符串爲 ,但您的程序顯然需要閱讀字符。

您還需要

#include <stdio.h> 

在開始。

哦,

name[j] < 25 

應該

j < MAX 

更多bug修正:

char name[MAX+1]; /* one more for the terminating 0 */ 

name[j]=0; /* instead of NULL */ 
+0

爲了顯示25個字符及以下的名稱,我們需要使用鍵盤上的4個箭頭鍵以及{},來輸入。等 – AgentPerry

+0

支持箭頭鍵等絕對超出了簡單答案的範圍,這需要更多的代碼。 –

0

你的程序是錯誤的因各種原因snipet代碼,例如

  • scanf("%s", name[j]);%s需要一個指向char陣列。
  • name[j] = NULL;,NULL是一個指針類型

相反,我建議你一個更清潔的算法中。檢查你是否喜歡它。

  1. 使用fgets()閱讀用戶輸入。
  2. 使用strpbrk()搜索*#或任何其他(如果需要)的存在。
  3. 如果strpbrk()返回NULL,這意味着,您可以進一步使用輸入。 restictedchars不存在。
  4. 否則,請再次輸入。

這就是說,void main(void)不考慮main()推薦的簽名,你應該使用int main(void)代替。