• 全部
...

请问下面这个程序,除了ctrl+z结束循环外,怎样正常退出循环?

aoshuanghanmei 2013-12-05 10:43:29
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

using namespace std;

struct node
{
char word[122];
int num;
}N[10000];

int main()
{
int flag = 0;
char c;
int i = 0;
char name[122];
int len = 0;

for(int k = 0; k < 10001; k++)
{
memset(N[k].word, '\0', sizeof(char)*122);
N[k].num = 0;
}

while(scanf("%c", &c) != EOF)
{
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= 0 && c <= 9))
{
if(flag == 0)
{
flag = 1;
i = 0;
}
if(c >= 'A' && c <= 'Z')
c = c - 'A' + 'a';
name[i++] = c;
}
else
{
if(flag == 1)
{
flag = 0;
name[i] = '\0';
bool tag = false;
for(int j = 0; j < len; j++)
{
if(strcmp(N[j].word, name) == 0)
{
N[j].num++;
tag = true;
break;
}
}
if(!tag)
{
strcpy(N[len].word, name);
N[len++].num++;
}
}
}
}
char list[10000][122];

int max = 0, cnt = 0;
for(int k = 0; k < len; k++)
{
if(max < N[k].num)
{
max = N[k].num;
cnt = 0;
strcpy(list[cnt++], N[k].word);
}
else if(max == N[k].num)
strcpy(list[cnt++], N[k].word);
else
continue;
}

char temp[122];
for(int j = 0; j < cnt; j++)
{
for(int k = j + 1; k < cnt; k++)
{
if(strcmp(list[j], list[k]) > 0)
{
strcpy(temp, list[j]);
strcpy(list[j], list[k]);
strcpy(list[k], temp);
}
}
}

printf("%d occurrences\n", max);
for(int k = 0; k < cnt; k++)
{
printf("%s\n", list[k]);
}

return 0;
}
...全文
给本帖投票
122 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
aoshuanghanmei 2013-12-05
  • 打赏
  • 举报
回复
引用 6 楼 wusuopuBUPT 的回复:
引用 3 楼 aoshuanghanmei 的回复:
我这是HOJ上的题,题目里没有说遇到什么特定字符结束循环,只是说输入在end of file时结束。所以很困扰该怎样结束循环,除了强制结束的方法。
OJ的题目多数是这样做的。
但我这样做是不能跳出循环,给数据结果的啊。。。
d4shman 2013-12-05
  • 打赏
  • 举报
回复
引用 3 楼 aoshuanghanmei 的回复:
我这是HOJ上的题,题目里没有说遇到什么特定字符结束循环,只是说输入在end of file时结束。所以很困扰该怎样结束循环,除了强制结束的方法。
OJ的题目多数是这样做的。
d4shman 2013-12-05
  • 打赏
  • 举报
回复
因为scanf函数是有返回值的,他的返回值是读入数据的个数,操作系统里EOF默认是int的1,所以可以这样判断:
while(scanf("%c", &c)==1){

}
也可这样判断:
while(scanf("%c", &c) != EOF){
}
都是一个道理。 怎样让操作系统知道你已经输入完毕了呢? --通过向OS发送控制信号:
SIGINT   ^C   (default action: terminate the process)
SIGQUIT  ^\   (default action: terminate the process and dump to a core file)
SIGSUSP  ^Z   (default action: suspend the process)
OS会捕获信号,然后判断并作出处理。
lm_whales 2013-12-05
  • 打赏
  • 举报
回复
while(scanf("%c", &c)==1){ .... }
aoshuanghanmei 2013-12-05
  • 打赏
  • 举报
回复
我这是HOJ上的题,题目里没有说遇到什么特定字符结束循环,只是说输入在end of file时结束。所以很困扰该怎样结束循环,除了强制结束的方法。
max_min_ 2013-12-05
  • 打赏
  • 举报
回复

  while(scanf("%c", &c) != EOF) //这里的判断就是遇到EOF结束循环的阿

//可以在输入的时候判断c的值
  while(scanf("%c", &c) != EOF)
{
  //do something

  if( c== 'q')
  {
     break;
  }
}
空的 2013-12-05
  • 打赏
  • 举报
回复
ctrl + c ... ctrl + d ...

70,017

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧

手机看
关注公众号

关注公众号

客服 返回
顶部