2014-02-10 26 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