|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXTITL 40
#define MAXAUTL 40
#define MAXBKS 100
struct book
{
char title[MAXTITL];
char author[MAXAUTL];
float value;
};
int main(void)
{
struct book library[MAXBKS];
int count = 0;
int index;
int i, j;
printf("Please enter the book title.\n");
printf("Press [enter] at the start of a line to stop.\n");
while (count < MAXBKS && gets(library[count].title) != NULL && library[count].title[0] != '\0')
{
printf("Now enter the author.\n");
gets(library[count].author);
printf("Now enter the value.\n");
scanf("%f", &library[count++].value);
while (getchar() != '\n')
continue;
if (count < MAXBKS)
printf("Enter the next title.\n");
}
if (count > 0)
{
printf("Here is the list of your books:\n"); //原本输入输出
for (index = 0; index < count; index++)
printf("%s by %s: $%.2f\n", library[index].title, library[index].author, library[index].value);
printf("\n");
printf("Array by title.\n"); //按标题排序
for (i = 0; i < count - 1; i++)
{
for (j = i + 1;i < count; j++)
{
struct book temp;
if (strcmp(library[i].title, library[j].title) > 0)
{
temp = library[i];
library[i] = library[j];
library[j] = temp;
}
}
}
for (index = 0; index < count; index++)
printf("%s by %s: $%.2f\n", library[index].title, library[index].author, library[index].value);
printf("\n");
printf("Array by price:\n");
for (i = 0; i < count - 1; i++)
{
for (j = i + 1; i < count; j++)
{
struct book temp;
if (library[i].value > library[j].value)
{
temp = library[i];
library[i] = library[j];
library[j] = temp;
}
}
}
for (index = 0; index < count; index++)
printf("%s by %s: $%.2f\n", library[index].title, library[index].author, library[index].value);
printf("\n");
}
else
printf("No books?Too bad.\n");
return 0;
}
为什么我的strcmp那里运行的问候会发生冲突
本帖最后由 Neverturnback 于 2019-7-31 21:19 编辑
for (j = i + 1; i < count; j++) //这边是j吧(两处都写错了),越界访问了所以会报错;写的时候注意一点
更改过后程序运行过了没有问题
|
|