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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.