[英]Finding the longest string name and length
I'm trying to write a program that allows me to find the longest string name after input. 我正在尝试编写一个程序,允许我在输入后找到最长的字符串名称。 So far:
至今:
#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;
}
This seemed to work for example: 例如,这似乎起作用:
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
But then this happened: 但是后来发生了:
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
And this: 和这个:
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
Not sure what's happened here. 不知道这里发生了什么。 Any suggestions?
有什么建议么?
You have to compare their length not the strings themselves: 您必须比较它们的长度而不是字符串本身:
scanf("%s", nam);
if (strlen(nam) > strlen(nnam)){
strcpy(nnam, nam);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.