专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > C语言

请见见程序中的数组有无初始化,哪些需要注意的

发布时间:2011-06-28 10:56:44 文章来源:www.iduyao.cn 采编人员:星星草
请看看程序中的数组有无初始化,哪些需要注意的
写一个函数,输入一行字符,将此字符串中最长的单词输出。

#include "stdafx.h"
#include "string.h"

int main(int argc, char* argv[])
{
char* strtru(char * Str, int x , int y);

char str[80], word[10];
char lword[20] = {0};
int i, j, a, b, l;
a = 0;
b = 0;

printf("请输入一行字符:\n");
gets(str);

l = strlen(str);

for(i = 0; i < l; i++)
{
while(1)
{
if(str[i] == ' ') break;
else
{
j = i;
a = i;
do
{
b = j;
j++;
}while(str[j] != ' ' && str[j] != '\0');

strcpy(word, strtru(str, a, b));
}

if(strlen(word) > strlen(lword))
strcpy(lword, word);

i = j;
break;
}
}

printf("\n");
puts(lword);

return 0;
}

char* strtru(char * Str, int x , int y)        /*截取字符串Str[x]到Str[y]*/
{
int i, j;
char buf[20];

for(i = 0; i < 20; i++)
buf[i] = 0;

for(i = x, j = 0; i <= y && j < 20; i++, j++)
{
buf[j] = Str[i];
}

return buf;

}
------解决方案--------------------

#include <iostream>
#include <string>       // string
#include <map>          // multimap
#include <functional>   // greater
#include <sstream>      // istringstream
#include <cstdlib>      // system("pause")
using namespace std;

typedef multimap<int, string, greater<int>>::iterator Iterator;

int main()
{
string s, buf;
multimap<int, string, greater<int>> str;    // greater<int>指定按key降序排列 
getline(cin, s);                            // 读取一行
istringstream ss(s);                        // 用字符流读取每个单词
while (ss >> buf)                           // 循环将每个单词加入multimap
{
str.insert(make_pair(buf.size(), buf));
}

Iterator beg = str.begin();
int i = beg->first;                         // i就是最长的单词长度
while (beg != str.end())
{
if (beg->first == i)
{
cout << beg->second << endl;
++beg;
}
else
{
break;
}
}
system("pause");
return 0;
}


输入:

it string abc buffer iter is stream

输出:

string
buffer
stream
请按任意键继续. . .
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: