注册 登录
编程论坛 C++教室

菜鸟新手求解 关于字符串的问题

qwerty7890p 发布于 2015-05-19 16:21, 951 次点击
问题:输入一个句子,输出第一个最长和最短的单词。

小弟编程如下,为啥运行不了?
#include<iostream>
using namespace std;
int main()
{
    string a[499];
    char t;
    int i=0;
    while((cin>>a[i++])&&(t=cin.get())!='\n');
    int j,Max=-1,Min=499,xn,nn;
    for(j=0;j<i;j++)
    {
        Min=a[j].size()<Min?(nn=j,a[j].size()):Min;        
        Max=a[j].size()>Max?(xn=j,a[j].size()):Max;
    }
    cout<<a[xn]<<endl<<a[nn]<<endl;
    return 0;
}
11 回复
#2
qwerty7890p2015-05-19 16:24
没有标点
#3
wmf20142015-05-19 16:28
单词是不是都靠空格或标点区分?
#4
wp2319572015-05-19 16:32
c 还好办  c++貌似有更简单的办法  不是很了解
#5
qwerty7890p2015-05-19 16:37
回复 3楼 wmf2014
嗯,用空格,没有标点符号。
#6
qwerty7890p2015-05-19 16:38
回复 4楼 wp231957
用c处理字符串太麻烦,所以用了c++
#7
qwerty7890p2015-05-19 17:04
程序代码:
#include<iostream>

 using namespace std;

 int main()

 {
     string a[499];
     char t;
     int i=0;
     while((cin>>a[i++])&&(t=cin.get())!='\n');
     int j,Max=-1,Min=499,xn,nn;
     for(j=0;j<i;j++)
     {
         Min=a[j].size()<Min?(nn=j,a[j].size()):Min;      
         Max=a[j].size()>Max?(xn=j,a[j].size()):Max;
     }
     cout<<a[xn]<<endl<<a[nn]<<endl;
     return 0;

 }

真的没人看吗?
#8
yangfrancis2015-05-19 17:15
哪条语句在识别空格来着?
#9
qwerty7890p2015-05-19 17:33
回复 8楼 yangfrancis
cin.get()
#10
rjsp2015-05-20 10:51
程序代码:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main( void )
{
    std::string line;
    std::getline( cin, line );

    std::string word_shortest, word_longest;

    std::istringstream is( line );
    for( std::string word; is>>word; )
    {
        if( word_shortest.empty() || word.size()<word_shortest.size() )
            word_shortest = word;

        if( word.size() > word_longest.size() )
            word_longest = word;
    }

    cout << word_shortest << '\n';
    cout << word_longest << endl;
    return 0;
}
#11
qwerty7890p2015-05-21 18:53
回复 10楼 rjsp
抱歉,我更想知道的是错在哪?有劳了,如果没有更好的回复我就选你吧。
#12
wmf20142015-05-21 21:27
回复 11楼 qwerty7890p
你有两处错误:
1、需要#include<string>
2、a[j].size是无符号整形数,需要进行转换才能比较,否则-1是无符号里最大的数,得不到正确结果
你的代码修改如下,可得到正确答案:
程序代码:
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string a[499];
    char t;
    int i=0;
    while((cin>>a[i++])&&(t=cin.get())!='\n');
    int j,Max=-1,Min=499,xn,nn;
    for(j=0;j<i;j++)
    {
        Min=a[j].size()<Min?(nn=j,a[j].size()):Min;      
        Max=(int)a[j].size()>Max?(xn=j,a[j].size()):Max;
    }
    cout<<a[xn]<<endl<<a[nn]<<endl;
    return 0;
}

1