C程序:命令行使用argv,argc,读入链表

时间:2014-04-17 20:25:33

标签: c command-line linked-list argv argc

我有一个程序读取命令行提示添加

的链接列表
one two three 

进入列表。我正在使用

进行编译
gcc -o code code.c 

但是在我运行时的第二个提示

./code one two three 

它还将./code添加到列表的开头,使其成为

./codeonetwothree

当我只想要

onetwothree

如果没有将./code添加到我的链接列表中如何编译的任何建议将非常感谢!

如果需要,以下是我的代码:

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

typedef struct list_node_s{
    char the_char;
    struct list_node_s *next_node;
}list_node;

void insert_node(list_node *the_head, char the_char);
void print_list(list_node *the_head);

int main(int argc, char *argv[]){

    list_node the_head = {'\0', NULL};
    int the_count, the_count2;
    for(the_count = 0; the_count < argc; the_count++){
            for(the_count2 = 0; argv[the_count][the_count2] != '\0'; the_count2++){
                    char next_char = argv[the_count][the_count2];
                    insert_node(&the_head, next_char);
            }
    }

    print_list(&the_head);
    int nth_node = 3;
    printf("Node at the %d spot: ", nth_node);
    printf("%c \n", the_nth_node(&the_head, nth_node));
    return (0);
}

void insert_node(list_node *the_head, char the_char){

   list_node * current_node = the_head;
   while (current_node->next_node != NULL) {
    current_node = current_node->next_node;
   }
  current_node->next_node = malloc(sizeof(list_node));
  current_node->next_node->the_char = the_char;
  current_node->next_node->next_node = NULL;
}

void print_list(list_node *the_head){
    if(the_head == NULL){
            printf("\n");
    }else{
            printf("%c", the_head->the_char);
            print_list(the_head->next_node);
    }

}
int the_nth_node(list_node* head, int index_of)
{
  list_node* current_node = head;
  int count_1 = 0; /* the index of the node we're currently
              looking at */
  while (current_node != NULL)
  {
   if (count_1 == index_of)
      return(current_node->the_char);
   count_1++;
   current_node = current_node->next_node;
  }
}

2 个答案:

答案 0 :(得分:1)

arg [0]是正在执行的文件的名称。所以你应该用1

初始化你的外循环计数器
for(the_count = 1; the_count < argc; the_count++){
            for(the_count2 = 0; argv[the_count][the_count2] != '\0'; the_count2++){
                    char next_char = argv[the_count][the_count2];
                    insert_node(&the_head, next_char);
            }
    }

答案 1 :(得分:1)

argv[0]是该计划的名称。

如果您不想要该程序的名称,请在argv[1]

处开始处理
for(the_count = 1; the_count < argc; the_count++){