一个c语言练习的小问题(颠倒单词顺序,求指点)

ghostviper 2012-03-18 10:43:00
RT我c新手,写了这样一个程序,题目要求是输入一串字符(exp:you can cage a swallow cant'you?),然后要求这样输出(exp:you cant’swallow a cage can you?),额按照提示思路是这样的,循环逐个读取字符,将其存入一个字符数组,当遇到‘?’,‘!’,‘.’终止循环,将终止符存入一个字符变量,再用一个循环反向搜索数组,找到最后一个单词起始位置显示最后一个单词,然后在反向搜索倒数第二个,依次继续,最后显示出终止的符号。
额,我实在太笨了,只有照葫芦画瓢写了如下:
#include<stdio.h>
void main()
{
char sentence[50];
char temp,temp_end;
int count=0,i=0,temp_count=0,j=0;
temp=getchar();
while(temp!='!' && temp!='?' && temp!='.' && temp!='\n')//语句终止符号
{
sentence[i]=temp;
i++;
temp=getchar();
}
sentence[i]=temp;
temp_end=temp;
count=i-1;
while(count>=0)
{
if(sentence[count]==' ')
{
temp_count=count-1;
for(j=count+1;j<=count;j++)
{
printf("%c",sentence[j]);
}
count=temp_count;
}
count--;
}
printf("%c",temp_end);
}
分数是少了点,我第一次发帖,请海涵。。求指点啊,调试不过啊,改了好几次了。
...全文
376 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
ghostviper 2012-03-18
  • 打赏
  • 举报
回复
感谢4L的同志为我整理了思路,确实我的思路有点换乱,如你所说的:
#include<stdio.h>
void main()
{
char sentence[50];
char temp,temp_end;
int count=0,i=0,temp_count=0,j=0;
temp=getchar();
while(temp!='!' && temp!='?' && temp!='.' && temp!='\n')//语句终止符号
{
sentence[i]=temp;
i++;
temp=getchar();
}
sentence[i]=temp;
temp_end=temp;
count=i-1;
while(i>=0)
{
if(sentence[i]==' ')
{
temp_count=i-1;
for(j=i+1;j<=count;j++)
{
printf("%c",sentence[j]);
}
printf(" ");
count=temp_count;
}
i--;
}
printf("%c",temp_end);
}
额,可以实现倒数第一个单词以及终止符号的输出,但是倒数第二以及往前的就没法输出了,我又做了修改可以实现了。谢谢你,谢谢回帖的朋友们。
#include<stdio.h>
void main()
{
char sentence[50];
char temp,temp_end;
int count=0,i=0,temp_count=0,j=0;
temp=getchar();
while(temp!='!' && temp!='?' && temp!='.' && temp!='\n')//语句终止符号
{
sentence[i]=temp;
i++;
temp=getchar();
}
sentence[i]=temp;
temp_end=temp;
count=i-1;
while(i>0)
{
if(sentence[i]==' ')
{
temp_count=i-1;
for(j=i+1;j<=count;j++)
{
printf("%c",sentence[j]);
}
printf(" ");
count=temp_count;
}
i--;
if(i==0)
{
for(j=0;j<=count;j++)
{
printf("%c",sentence[j]);
}
}
}
printf("%c",temp_end);
}
hwcheng555 2012-03-18
  • 打赏
  • 举报
回复
用得这么复杂吗
ProgrammingRing 2012-03-18
  • 打赏
  • 举报
回复
指针数组可以吗……
shyrgst 2012-03-18
  • 打赏
  • 举报
回复
#include<stdio.h>
void main()
{
char sentence[50];
char temp,temp_end;
int count=0,i=0,temp_count=0,j=0;
temp=getchar();
while(temp!='!' && temp!='?' && temp!='.' && temp!='\n')//语句终止符号
{
sentence[i]=temp;
i++;
temp=getchar();
}
sentence[i]=temp;
temp_end=temp;
count=i-1;
while(i>=0)
{
if(sentence[i]==' ')
{
temp_count=i-1;
for(j=i+1;j<=count;j++)
{
printf("%c",sentence[j]);
}
printf(" ");
count=temp_count;
}
i--;
}
printf("%c",temp_end);
}
我在LZ的基础上修改了一下,不过按照你输出习惯,你在输入的时候最好一开始有一个空格,毕竟你是以空格还判断单词的
shyrgst 2012-03-18
  • 打赏
  • 举报
回复
for(j=count+1;j<=count;j++)
你这句逻辑很明显说不通嘛
ghostviper 2012-03-18
  • 打赏
  • 举报
回复
额,题目规定只能用一维的。帮忙看下我是不是思路哪里有问题了,谢谢了。我实在看不出来才来提问的
疼你 2012-03-18
  • 打赏
  • 举报
回复
随便瞄一眼,我的第一反应是你可以用个二维数组存放各个单词。。然后反过来输出就行了。。

69,336

社区成员

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

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