2017-03-17 105 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

相關問題