我试图编写一个程序,允许我在输入后查找最长的字符串名称。到目前为止:查找最长的字符串名称和长度
#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
不知道发生了什么这里。有什么建议么?
你怎么能指望'LEN = STRCMP(nnam,NAM);'会给你的字符串长度的比较? – tod 2014-12-07 06:31:43
我认为这是因为我认为strcmp函数已经在查看字符串长度的差异了。猜猜我错了。 – 2014-12-07 06:35:01
我回滚了你的“固定”编辑。 “解决”问题,并添加“解决”到yheir标题,将Stack Overflow的目的作为*问题和答案*存储库。作为新成员,您可能不知道这一点;请参阅[入门教程](http://stackoverflow.com/tour)并阅读[帮助中心](http://stackoverflow.com/help)。如果没有现有答案有帮助,您可以自己添加答案。 – usr2564301 2014-12-07 10:33:24