[英]Finding the longest string name and length
我正在尝试编写一个程序,允许我在输入后找到最长的字符串名称。 至今:
#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
不知道这里发生了什么。 有什么建议么?
您必须比较它们的长度而不是字符串本身:
scanf("%s", nam);
if (strlen(nam) > strlen(nnam)){
strcpy(nnam, nam);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.