返回信息流一个简单的小程序:从文件中读入一条公交路线,然后存储成链表的形式输出
#include <stdio.h>
#include <stdlib.h>
struct line_node
{
char line_name[3];
struct stop_node *first_stop;
};
struct stop_node
{
char stop_name[10];
struct stop_node *next_stop;
};
int main()
{
FILE *in,*out;
char infile[10], outfile[10],ch;
struct line_node *line;
struct stop_node *stop, *ptr;
int i=0;
line=(struct line_node *)malloc(sizeof(struct line_node));
line->first_stop=NULL;
ptr=stop=(struct stop_node *)malloc(sizeof(struct stop_node));
stop->next_stop=NULL;
printf ("Enter the infile name:\n");
scanf ("%s", infile); //源文件是 my1.c
if ((in=fopen(infile,"r")) == NULL)
{
printf ("cannot open infile\n");
exit (0);
}
ch=fgetc(in);
while (!feof(in))
{
putchar(ch);
if ((ch >= '0') && (ch <= '9'))
{
line->line_name[i]=ch;
i++;
}
else if (ch == '\n')
{
i=0;
line->first_stop=ptr;
}
else if (ch == '-')
{
ptr->stop_name[i++]='\0';
i=0;
stop=(struct stop_node *)malloc(sizeof(struct stop_node));
stop->next_stop=NULL;
ptr->next_stop=stop;
ptr=stop;
}
else
{
ptr->stop_name[i++]=ch;
}
ch=fgetc(in);
}
putchar('\n');
puts(line->line_name);
ptr=line->first_stop;
while(ptr)
{
printf("%s-", ptr->stop_name);
ptr=ptr->next_stop;
}
putchar('\n');
fclose(in);
return 0;
}
但输出的结中参杂着乱码(见附件)
附件(860.7KB)
输入的文件内容是:
304
巴沟村公交场站-巴沟村-海淀南路西口-海淀南路-海淀黄庄东-知春里-知春里东站(路口东)-知春路-学知桥南-蓟门桥北-蓟门桥南-明光桥北-明光桥东-北京师范大学南门-铁狮子坟-北太平桥北-牡丹园
请问:为什么会有乱码出现?怎么才能除去乱码?
这是一条镜像帖。来源:北邮人论坛 / cpp / #32328同步于 2009/11/28
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
请教大牛 文件输出内容中为何有乱码
salooloo
2009/11/28镜像同步3 回复
订阅后,新回复会通过你的通知中心匿名送达。
3 条回复
1: 304后面的乱码是因为你puts的字符串没有以'\0'结束
2:长站名后的乱码是站名越界了(1个汉字可能需要2个bytes)
3:还有一些其它的问题
字符串处理,似乎c++是强项
【 在 salooloo 的大作中提到: 】
: 一个简单的小程序:从文件中读入一条公交路线,然后存储成链表的形式输出
: #include <stdio.h>
: #include <stdlib.h>
: ...................
谢大牛!
【 在 wifil 的大作中提到: 】
: 1: 304后面的乱码是因为你puts的字符串没有以'\0'结束
: 2:长站名后的乱码是站名越界了(1个汉字可能需要2个bytes)
: 3:还有一些其它的问题
: ...................