代码如下:
#include
#include
#define MaxSize 50
typedef char ElemType;
typedef struct
{
ElemType data[MaxSize];
int length;
} SqList;
void CreateList(SqList *&L,ElemType a[],int n)
{
L=(SqList *)malloc(sizeof(SqList));
for(int i=0;idata[i]=a[i];
L->length=n;
}
void InitList(SqList *&L)
{
L=(SqList *)malloc(sizeof(SqList));
L->length=0;
}
void DispList(SqList *L)
{
for(int i=0;ilength;i++)
printf("%c",L->data[i]);
printf("\n");
}
bool ListInsert(SqList *&L,int i,ElemType e)
{
int j;
if(i<1||i>L->length+1||L->length==MaxSize)
return false;
i--;
for(j=L->length;j>i;j--)
L->data[j]=L->data[j-1];
L->data[i]=e;
L->length++;
return true;
}
int main()
{
SqList *L;
ElemType e;
printf("顺序表的基本运算如下:\n");
printf("(1)初始化顺序表L\n");
InitList(L);
printf("(2)依次插入啊,吧,从,的,额元素\n");
ListInsert(L,1,'啊');
ListInsert(L,2,'吧');
ListInsert(L,3,'从');
ListInsert(L,4,'的');
ListInsert(L,5,'额');
printf("(3)输出顺序表L:");
DispList(L);
return 1;
问题:
代码是我摘抄的。我想要顺序表输出“啊吧从的额”,但是它输不出来。把“abcde”插入顺序表,又可以输出来。感觉是插入英文可以,中文不行,这是什么原因?
程序结果如下:
ListInsert(L,1,'啊');
中文是字符串,要用双引号。你这个顺序表是字符表,只能存储单个字符,不能存储中文,存储中文要用字符串
这么改,供参考:
#include<stdio.h>
#include<malloc.h>
#include<string.h> //修改
#define MaxSize 50
typedef char ElemType;
typedef struct
{
ElemType data[MaxSize][4]; // 修改
int length;
} SqList;
void CreateList(SqList*& L, ElemType* a[], int n) // 修改
{
L = (SqList*)malloc(sizeof(SqList));
for (int i = 0; i < n; i++)
strcpy(L->data[i], a[i]); //L->data[i] = a[i]; 修改
L->length = n;
}
void InitList(SqList*& L)
{
L = (SqList*)malloc(sizeof(SqList));
L->length = 0;
}
void DispList(SqList* L)
{
for (int i = 0; i < L->length; i++)
printf("%s", L->data[i]); // 修改
printf("\n");
}
bool ListInsert(SqList*& L, int i, ElemType* e) //修改
{
int j;
if (i<1 || i>L->length + 1 || L->length == MaxSize)
return false;
i--;
for (j = L->length; j > i; j--)
strcpy(L->data[j], L->data[j - 1]); //L->data[j] = L->data[j - 1]; 修改
strcpy(L->data[i], e); //L->data[i] = e; 修改
L->length++;
return true;
}
int main()
{
SqList* L;
ElemType e;
printf("顺序表的基本运算如下:\n");
printf("(1)初始化顺序表L\n");
InitList(L);
printf("(2)依次插入啊,吧,从,的,额 元素\n");
ListInsert(L, 1, "啊"); //修改
ListInsert(L, 2, "吧"); //修改
ListInsert(L, 3, "从"); //修改
ListInsert(L, 4, "的"); //修改
ListInsert(L, 5, "额"); //修改
printf("(3)输出顺序表L:");
DispList(L);
return 1;
}