我正在尝试编写一个程序,允许我在输入后找到最长的字符串名称。到目前为止:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
int i;
int tot[20];
int len; /*length of string*/
char nam[20]; /*the variable the user will be entering*/
char nnam[20]; /*new name variable.
where the longest is kept*/
for (i = 0; i < 6; i++){ /*user input of 6 strings*/
printf("Enter a string: ");
scanf("%s", nam);
len = strcmp(nnam, nam); /*comparing length of input
to stored string*/
if (len > 0){ /*condition*/
strcpy(nnam, nam); /*should copy the largest
value into nnam*/
}
}
printf("The longest string is: %s\n", nnam);
printf("The string length is: %d\n", strlen(nnam));
return 0;
}
这似乎有用:例如:
FIRST OUTPUT:
Enter a string: red
Enter a string: red
Enter a string: purple
Enter a string: red
Enter a string: red
Enter a string: red
The longest string is: purple
The string length is: 6
但后来发生了这件事:
SECOND OUTPUT:
Enter a string: blue
Enter a string: black
Enter a string: red
Enter a string: purple
Enter a string: gold
Enter a string: green
The longest string is: black
The string length is: 5
而且:
THIRD OUTPUT:
Enter a string: red
Enter a string: red
Enter a string: purple
Enter a string: gold
Enter a string: red
Enter a string: red
The longest string is: gold
The string length is: 4
不确定这里发生了什么。有什么建议吗?
答案 0 :(得分:2)
你必须比较它们的长度而不是字符串本身:
scanf("%s", nam);
if (strlen(nam) > strlen(nnam)){
strcpy(nnam, nam);
}