【问题标题】:C - Reading a string & int from stdin (or redirect from file)C - 从标准输入读取字符串和整数(或从文件重定向)
【发布时间】:2017-08-09 12:56:40
【问题描述】:

首次在 Stack Overflow 上发帖,向任何可以提供帮助的人欢呼。

我的主程序有问题,它应该“从标准输入(或从文件重定向)读取字符串和整数对(字符串后跟 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 循环来测试字符串和 int 是否都被正确读取,但我的实现是错误的(程序在到达 while 循环时崩溃)。

我在这里完全走错了吗?还是有一个我完全错过的逻辑错误?再次感谢!

【问题讨论】:

  • 我必须说的第一次发帖很好。

标签: c while-loop scanf


【解决方案1】:

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

同样去掉while循环底部的scanf,没必要。

【讨论】:

  • 非常感谢@cleblanc!关于内存分配,我完全放屁,并删除了多余的 scanf。工作至今!
【解决方案2】:

您的代码存在一些问题:

  • 假设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);
    }
    

【讨论】:

  • 注意:"ms" 中的 m 不是 scanf() 的标准 C 库的一部分。
猜你喜欢
  • 1970-01-01
  • 2018-08-05
  • 1970-01-01
  • 2012-07-21
  • 2011-03-30
  • 1970-01-01
  • 1970-01-01
  • 2019-07-26
  • 1970-01-01
相关资源
最近更新 更多