printf的问题,请各位老师帮忙看下,不胜感激

andykuo 2010-04-21 07:14:41
问个小问题,小弟正在看 C语言程序设计 ,我一般都是看到一个例子,先盖住自己写出来然后跟编译运行跟书上的对照,前面都还好今天看到这里,有个小问题搞了半天都没弄明白。
程序功能就是读一段文字,然后找出最长的一句输出来
就是下面代码我自己写的,我加红了那里,用printf 输出的总是只输出第一个字母就没有了,只有用下面的那个循环的方式才能打印出整个句子来



#include <stdio.h>
#define MAX 1000

int getline(int c[]);//get a line for cin,return the longth of the line
int copy(int s[],int t[]);//copy s[] to t[]
main(){
int max,n,i;
int longest[MAX],store[MAX];
max=0;
while((n=getline(store))!=0)
if(n>max) { //if the new line if longer
max=n; // then update max,and store the new line
copy(store,longest);
}
printf("%s\n",longest);//print the longgest one
for(i=0;longest[i]!='\0';i++) putchar(longest[i]);//the same as printf

}
int getline(int ch[MAX]){
int i,n,c;
i=0;
while(i<MAX&&(c=getchar())!=EOF&&c!='\n')
{ ch[i]=c;i++;}
if(c=='\n')
{ch[i]=c;i++;}
ch[i]='\0';
return i;
}
int copy(int s[],int t[]){
int i;
i=0;
while((t[i]=s[i])!='\0')
i++;
return 0;
}
...全文
108 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
andykuo 2010-04-22
  • 打赏
  • 举报
回复
谢谢各位老师
yiruirui0507 2010-04-21
  • 打赏
  • 举报
回复
int longest[MAX],store[MAX];

换成

char longest[MAX], store[MAX];
saishow 2010-04-21
  • 打赏
  • 举报
回复
早上我也遇到个问题。问题就是int + char在一条语句printf输出。搞了半天。
ccc_cgreen 2010-04-21
  • 打赏
  • 举报
回复
longest 是int*,这个里面放的是一个int类型,占4个字节,你从屏幕上输入的是char类型,赋值给该int的时候,只是修改了最低位一个字节,其他三个字节全是0,比如说char a = '1';int b = a;
那么a就是0x0000001F,而printf打印的时候,如果发现0就会终止,也就是说此处只会输出1.像上面说的把int改为char类型就可以了。
huanmie_09 2010-04-21
  • 打赏
  • 举报
回复
完整版:

#include <stdio.h>
#define MAX 1000

int getline(char c[]);//get a line for cin,return the longth of the line
int copy(char s[],char t[]);//copy s[] to t[]

int main()
{
int max,n,i;
char longest[MAX], store[MAX];

max=0;
while((n=getline(store))!=0)
if(n>max) { //if the new line if longer
max=n; // then update max,and store the new line
copy(store,longest);
}
printf("%s\n",longest);//print the longgest one
for(i=0;longest[i]!='\0';i++) putchar(longest[i]);//the same as printf
}

int getline(char ch[MAX])
{
int i,n,c;
i=0;
while(i<MAX&&(c=getchar())!=EOF&&c!='\n')
{
ch[i]=c;
i++;
}
if(c=='\n')
{
ch[i]=c;
i++;
}
ch[i]='\0';
return i;
}

int copy(char s[],char t[])
{
int i;
i=0;
while((t[i]=s[i])!='\0')
i++;
return 0;
}
stjay 2010-04-21
  • 打赏
  • 举报
回复
printf("%s\n",longest);
longest是char数组才能printf出来
而这里longest是int数组
localxiao 2010-04-21
  • 打赏
  • 举报
回复
int longest[MAX],store[MAX];

换成

char longest[MAX], store[MAX];
andykuo 2010-04-21
  • 打赏
  • 举报
回复
晕了 代码里不能加红了

69,371

社区成员

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

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