C - 读一个字符串&来自stdin的int(或从文件重定向)

时间:2017-03-17 20:20:13

标签: c while-loop scanf

Stack Overflow的首次海报,为任何可以提供帮助的人欢呼。

我的主程序出现问题,该程序应“从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);
}

我尝试使用带有scanf条件== 2的while循环来测试是否正确读取了string和int,但是我的实现是错误的(程序在到达while循环时崩溃)。

我在这里走错了路吗?或者是否存在一个逻辑错误,我只是缺失了?再次感谢!

2 个答案:

答案 0 :(得分:3)

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

同时从while循环的底部删除scanf,这不是必需的。

答案 1 :(得分:0)

您的代码存在一些问题:

  • 假设bstree_insert没有复制字符串str,您必须自己为每次循环迭代分配它,或者在%ms中使用scanf()格式。< / p>

  • 您将*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);
    }