以文本方式查看主题

-  计算机科学论坛  (http://bbs.xml.org.cn/index.asp)
--  『 编程心得 』   (http://bbs.xml.org.cn/list.asp?boardid=42)
----  [求助]  (http://bbs.xml.org.cn/dispbbs.asp?boardid=42&rootid=&id=28404)


--  作者:jack_yin666
--  发布时间:3/10/2006 1:06:00 PM

--  [求助]
我编了一个将一个字符串放入链表中然后打印出来,但是打印出来后老是出现很多的‘['.下面是我的源程序:
#include <stdio.h>
#include <malloc.h>
typedef   struct  my_char
{
    char   c;
    struct  my_char   *next;
}Node;

Node * string_to_list(char *s)
{

    Node   *head ,*tail;
    int   i=0;
    if(s[i]!='\0'){
        head=(Node *)malloc(sizeof(Node));
        tail=head;
        tail->c='s[0]';
     }  
    for(i=1;s[i]!='\0';++i){
         tail->next=(Node*)malloc(sizeof(Node));
         tail=tail->next;
         tail->c='s[i]';
     }  
     tail->next=NULL;
     return head;
}
void print(Node *head)
{    int n;
      Node *p;
      p=head;
      if(head!=NULL)
         do
              {
                        printf("%c",p->c);
                        p=p->next;
              } while(p!=NULL);
}
void main()
{
    char    *s="my name is yinchao!";
    Node  *head;
    head=string_to_list(s);
    print(head);
}
     


--  作者:elfstone
--  发布时间:3/11/2006 10:18:00 AM

--  
去掉我给你标示出的两个单引号,程序就对了,从char*中取出单个成员其类型为char
#include <stdio.h>
#include <malloc.h>
typedef   struct  my_char
{
    char   c;
    struct  my_char   *next;
}Node;

Node * string_to_list(char *s)
{

    Node   *head ,*tail;
    int   i=0;
    if(s[i]!='\0'){
        head=(Node *)malloc(sizeof(Node));
        tail=head;
        tail->c=s[0];      /*s[0]本身是字符型,不必加单引号*/  
     }  
    for(i=1;s[i]!='\0';++i){
         tail->next=(Node*)malloc(sizeof(Node));
         tail=tail->next;
         tail->c=s[i];   /*此处也是*/
     }  
     tail->next=NULL;
     return head;
}
void print(Node *head)
{    int n;
      Node *p;
      p=head;
      if(head!=NULL)
         do
              {
                        printf("%c",p->c);
                        p=p->next;
              } while(p!=NULL);
}
int main()
{
    char    *s="my name is yinchao!";
    Node  *head;
    head=string_to_list(s);
    print(head);
    system("PAUSE");
}


W 3 C h i n a ( since 2003 ) 旗 下 站 点
苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
46.875ms