2017-03-17 106 views
3

第一次张贴到Stack Overflow,招呼任何可以帮助的人。C - 从标准输入读取字符串&int(或从文件重定向)

我的主程序遇到问题,它应该“从stdin(或从文件重定向)读取字符串和整数对(字符串后跟int,每行一对)并按照它们的顺序插入这些对读入最初为空的二叉搜索树。“

已经测试了二叉搜索树插入&使用提供的测试用例本身,我知道我的插入&遍历工作。但是,我努力在同一行读取字符串& int,并且不确定如何实现文件重定向(我可以在UNIX服务器上使用cat命令将其上传到?)。

这里是我的main.c

#include <stdio.h> 
#include "bst.h" 

int main(void) 
{ 
    BStree bst; 
    int size; 
    char quit; 
    char *str; 
    int num; 
    printf("Please enter the size of the tree: "); 
    scanf("%d", &size); 
    bst = bstree_ini(size); 
    printf("Please enter the first key (str) & data (int) you wish to enter, separated by whitespace: "); 
    while ((scanf(" %s %d", str, &num)) == 2) { 
     bstree_insert(bst, *str, num); 
     printf("Please enter Q/q if you wish to stop entering, else continue: "); 
     scanf(" %c", &quit); 
     if(quit == 'Q' || quit == 'q') 
      break; 
     printf("Please enter the new key (str) then the data (int): "); 
     scanf("%s %d", str, &num); 
    } 
    bstree_traversal(bst); 
    bstree_free(bst); 
} 

我试图用一个while循环用scanf函数条件== 2测试如果两个字符串和INT被正确读取,但是我的实现是错误的(程序崩溃在达到while循环时)。

我完全在错误的轨道上吗?还是有一个逻辑错误,我只是失去了平淡?再次感谢!

+0

不错的第一次后,我必须说。 –

回答

3

您需要为str分配内存,请尝试char str[256]而不是char * str。

也从while循环的底部删除scanf,这是没有必要的。

+0

非常感谢@cleblanc! 我完全脑部放屁关于内存分配,并删除了多余的scanf。迄今为止的作品! – kapkong

0

代码有几个问题:

  • 假设bstree_insert不重复的字符串str,您将自行分配它每次循环迭代或scanf()使用%ms格式。

  • 您插入*str到您的btree,但*str只引用字符串的第一个字符。

  • 您复制提示(Please enter the new key...),而不是将您的while循环转换为do ... while循环。

    int main(void) 
    { 
        BStree bst; 
        int size; 
        char quit; 
        char *str; 
        int num; 
        printf("Please enter the size of the tree: "); 
        scanf("%d", &size); 
        bst = bstree_ini(size); 
    
        do { 
        printf("Please enter the new key (str) then the data (int): "); 
        if (scanf("%ms %d", &str, &num) == 2) { 
         bstree_insert(bst, str, num); 
         printf("Please enter Q/q if you wish to stop entering, else continue: "); 
         scanf("%c", &quit); 
         if (quit == 'Q' || quit == 'q') 
          break; 
        } 
        else { 
         printf("Invalid key/data format\n"); 
         break; 
        } 
        } while (1); 
    } 
    
+0

注意:“ms”中的'm'不是'scanf()'的标准C库的一部分。 – chux

相关问题