这个循环哪里错了?

SHOUYU2 2010-10-26 06:47:06
如果输入回车的话,循环就结束。
然后打印出所有的title
但是好像判断条件错了。
怎样判断输入的是空格呢?

#include <stdio.h>
#include <string.h>
struct book
{

int id;
char title[20];
};
struct book item[10];
main()
{

int l=0;
puts("input the book title");
while(gets(item[l].title!=NULL)
{
item[l].id=l+1;
l++;
}
int k=0;
while(item[k].title!=0)
{
printf("id is%d,",item[k].id);
printf("内容是%s ",item[k].title);
k++;
}

getchar();

}




...全文
155 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
harleypang 2010-10-27
  • 打赏
  • 举报
回复
mark一个,学习兼挣分
车太靓 2010-10-27
  • 打赏
  • 举报
回复
learning
manytao 2010-10-27
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 hnuqinhuan 的回复:]

gets函数的原型是char * gets(char *s);当读取成功的时候返回s,所以这个程序里p的值是和a的值相同的。当gets读取发生错误时返回NULL
所以gets一般不会反悔NULL 只有在读取错误时才会出现
[/Quote]

正解
Losfree 2010-10-27
  • 打赏
  • 举报
回复
马克 学习了
碎碎念 2010-10-27
  • 打赏
  • 举报
回复

#include "stdafx.h"
#include <stdio.h>
#include <string>
struct book
{

int id;
char title[20];
};

struct book item[10];


int _tmain(int argc, _TCHAR* argv[])
{




int l=0;
puts("input the book title");
while(*gets(item[l].title) != 32) //判断空格,如果输入为一个空格就停止...
{
item[l].id=l+1;
l++;
}
int k=0;
while(k<l)
{
printf("id is%d,",item[k].id);
printf("内容是%s \n",item[k].title);
k++;
}




return 0;
}

無_1024 2010-10-26
  • 打赏
  • 举报
回复
gets函数的原型是char * gets(char *s);当读取成功的时候返回s,所以这个程序里p的值是和a的值相同的。当gets读取发生错误时返回NULL
所以gets一般不会反悔NULL 只有在读取错误时才会出现
千杯不醉-sen 2010-10-26
  • 打赏
  • 举报
回复


//空格也算啊,没法那样区分,用数字直接控制大小也行。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NUM_SIZE 10
#define MAXSIZE 20

struct book
{
int id;
char title[MAXSIZE];
};

void main( void )
{

int i = 0,k = 0;
struct book item[NUM_SIZE];
puts("input the book title");
do
{
gets(item[i].title);
item[i].id=i+1;
i++;
}while(i<NUM_SIZE);

while(k < i)
{
printf("id is%d,",item[k].id);
printf("内容是%s \n",item[k].title);
k++;
}
system("pause");
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NUM_SIZE 10
#define MAXSIZE 20

struct book
{
int id;
char title[MAXSIZE];
};

void main( void )
{

int i = 0,k = 0;
struct book item[NUM_SIZE];
puts("input the book title");
while( gets(item[i].title),strcmp(item[i].title,"") !=0 )
{
item[i].id=i+1;
i++;
}

while(k < i)
{
printf("id is%d,",item[k].id);
printf("内容是%s \n",item[k].title);
k++;
}
system("pause");
}
测试结果://多点一次回车
input the book title
123+回车
456+回车
789+回车
+回车
id is1,内容是123
id is2,内容是456
id is3,内容是789
请按任意键继续. . .
熊熊大叔 2010-10-26
  • 打赏
  • 举报
回复
1. while(gets(item[l].title!=NULL)这行有语法错误,少了一个)
2. 现在所有的软件开发中,gets是严格禁止使用的函数,就是这个函数引起的溢出攻击。
3. 第一个while循环会在输入CTRL+Z后结束
4. 由于title没有初始化,第二个循环可能产生异常。
  • 打赏
  • 举报
回复
换成scanf进行输入试试

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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