读书人

解释解决方案

发布时间: 2013-04-21 21:18:07 作者: rapoo

解释
#include<iostream>
#include<string>
using namespace std;
void main()
{
const int SIZE=20;
char buf[SIZE];
char *largest;
int curLen,maxLen=-1,cnt=0;
cout<<"输入单词:\n";
while(cin>>buf)
{curLen=strlen(buf);
cnt++;
if(curLen>maxLen)
{maxLen=curLen;
largest=buf;
}
}
cout<<endl;
cout<<cnt<<endl;
cout<<maxLen<<endl;
cout<<largest<<endl;
}

输入
if else case switch continue to break


预料结果为
6
8
continue

Press any key to continue



实际结果continue却没有输出!
6
8

Press any key to continue

[解决办法]
问题找到了,char *largest;
你这个根本就无法存储超过一个的字符,换成string largest就OK了
[解决办法]
是因为最后输入break的时候,buf已经被重置了


#include<iostream>
#include<string>
using namespace std;
void main()
{
const int SIZE=20;
char buf[SIZE];
char largest[20];;
int curLen,maxLen=-1,cnt=0;
cout<<"输入单词:\n";
while(cin>>buf)
{ curLen=strlen(buf);
cnt++;
if(curLen>maxLen)
{maxLen=curLen;
//largest=buf;
strcpy(largest,buf);// 改为
}
}
cout<<endl;
cout<<cnt<<endl;
cout<<maxLen<<endl;
cout<<largest<<endl;
}

[解决办法]
你的程序有三个问题:
(1)定义了没有初始化的指针char *largest,指针指代不明,所以运行时出现错误。
可以将其改为char largest[20];
(2)while循环没有终止条件,不知道你怎么还会有输出。建议通过判断buf的值给定一个循环终止条件。
比如if(strcmp(buf,"End")==0) break;
(3)保存最长字符串的时候应该用strcpy(largest,buf);
试一试

读书人网 >C++

热点推荐