2014-02-10 25 views
0
#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 

int main(){ 

int n, i, check=0; 
char first_name[20]; 
char current_name[20]; 

printf("Enter n, followed by n last names (each last name must be a single word):"); 
scanf("%d", &n); 
scanf("%s", &first_name[20]); 

for (i=1; i<n; i++){ 
    scanf("%s", &current_name[20]); 
    if (strcmp(first_name[20], current_name[20])==0) 
     check = 1; 
} 
    if (check == 1) 
    printf("First name in list is repeated."); 
else 
    printf("First name in list is not repeated."); 
system("pause"); 

return 0; 
} 

我使用開發的C++崩潰,我得到的錯誤是這樣的:程序與字符串和數組

23:9 [注意]傳遞「的strcmp」的參數1,使指針從整數,未作鑄[默認啓用]

的程序運行,但它崩潰後,我在鍵入幾個名字。

+1

OMG感謝ü傢伙!你所有的搖滾 – user3291455

+0

它固定然後接受答案。 –

回答

2
strcmp(first_name[20], current_name[20])==0) 

就好像是無效INSEAD使用strcmp(first_name,current_name)也爲

scanf("%s", &first_name[20]);改爲使用scanf("%s",first_name)

0

您沒有正確使用strcmp()。當將char []傳遞給一個函數時,您只需要使用它的名字。

所以,你需要解決以下問題:

  1. 變化

    if (strcmp(first_name[20], current_name[20])==0) 
    

    if (strcmp(first_name, current_name)) 
    
  2. 變化

    scanf("%s", &first_name[20]); 
    ... 
    scanf("%s", &current_name[20]); 
    

    scanf("%s", first_name); 
    ... 
    scanf("%s", current_name); 
    
0

這裏其他的答案會幫助,如果你只想要一個字符串工作。如果你想像你一樣使用字符串和數組,那麼你需要通過在循環中打印的輸出來聲明一個字符串數組,而不是單個字符串。

char first_name[20]; 

聲明一個字符數組(如果這些字符中的任何一個字符都是NUL),則爲一個字符串數組。你似乎想用一個字符串數組來工作,所以你需要字符的二維數組(或字符指針的數組,每個字符串的malloc):

char first_name[20][MAX_NAME_LENGTH]; 

其中MAX_NAME_LENGTH定義如上一樣:

#define MAX_NAME_LENGTH 64 

然後你就可以做的東西一樣:

strcmp(first_name[i], current_name[i]) 

由於first_name[i]將衰減到char *

0

在c/C++中,字符串只是一個char數組。 要訪問數組元素,可以使用指針。要從頭開始訪問字符串,必須提供指向字符串開頭的指針。

STRCMP和scanf取指針字符數組(因此,字符串):

int strcmp (const char * str1, const char * str2); 
int scanf (const char * format, ...); 

他們需要字符串指針的開頭。您可以一次:

scanf("%s", first_name); 
strcmp(first_name, current_name) == 0 

scanf("%s", &first_name[0]); 
strcmp(&first_name[0], &current_name[0]) == 0