解释
#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;
}