高手来!
#include <stdio.h>
#include <string.h>
#include <conio.h>
int f(char s[])
{
int i,m1,m2=0;
int fir,first,len;
if(s[0]!= ' ')
m1=1;
else
m1=0;
len=strlen(s);
for(i=0;i <len;i++)
{
if(s[i]!= ' ')
if(s[i-1]!= ' ')
m1++;
else
fir=i;
else
{
if(m1> =m2)
{
m2=m1;
first=fir;
m1=0;
}
}
}
printf( "the longest number:%d\n ",m2);
return(m2);
}
void main()
{
char s[100];
int i;
printf( "please input a line of words: ");
gets(s);
for(i=f(s);s[i]!= ' '&&s[i]!= '\0 ';i++)
printf( "%c ",s[i]);
printf( "\n ");
getch();
return;
}
我是新手刚学,偶然看到这个帖子所写的代码!下载回去运行了下,还是不行,希望高手出来改一下!在线等,非常急!题目是输入一行字符,统计出最长的那个单词!
[解决办法]
给你个Stl版的吧
#include "stdafx.h "
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
cout < < "please enter a line of words " < <endl;
string sTemp;
vector <string> svec;
//while(getline(cin,sTemp)){
getline(cin,sTemp);
istringstream stream(sTemp); //将每个字符串存入到vector容器中
while(stream> > sTemp)
svec.push_back(sTemp);
//}
typedef vector <string> ::size_type vec_size;
vec_size it=1;
for(vec_size sx=0;sx!=svec.size();++sx){ //循环读取容器的值
if(svec[sx].size()> it) //比较每个容器中字符串的长度
it=svec[sx].size();
}
cout < <it < <endl;
//cout < <svec[sx].size() < <endl;
}
[解决办法]
#include <sstream>
#include <string>
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
string line, str, s;
int len;
cout < < "Input a sentence: " < <endl;
getline(cin, line);
while(line != "exit ") //输入 exit 退出
{
len=0;
str= " ";
istringstream t(line);
while(t> > s)
if(s.length() > len) {len=s.length(); str=s;} //len 也需要保存最新的单词长度
cout < < "The max-len word is: " < <str < <endl;
cout < <endl < < "Input a sentence: " < <endl;
getline(cin, line);
}
system( "PAUSE ");
return 0;
}
[解决办法]
//C语言版本的, 修改了一下,不但找到最大的长度,并且把最大长度的单词也找出来
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char str[100];
char tempStr[100], maxLet[100];
char *pStr = str;
int len, i;
memset( pStr, 0, 100 );
printf( "please input a line of words: ");
gets( pStr );
len = 0;
while( *pStr != '\0 ' )
{
i = 0;
while( *pStr == ' ' )pStr++;
while( *pStr != ' '&& *pStr != '\0 ' )
{
*(tempStr+i) = *pStr;
i++;
*pStr++;
}
*(tempStr+i) = '\0 ';
if( len < i )
{
len = i;
strcpy( maxLet, tempStr );
}
}
printf( "The Max Length Letter:%s\n ", maxLet );
printf( "The Max Length:%d\n ", len );
system( "PAUSE ");
return 0;
}