第一次張貼到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循環時)。
我完全在錯誤的軌道上嗎?還是有一個邏輯錯誤,我只是失去了平淡?再次感謝!
不錯的第一次後,我必須說。 –