【问题标题】:Terminal command not executing properly终端命令未正确执行
【发布时间】:2021-12-04 15:13:13
【问题描述】:

当我在命令行中运行代码时,所有功能都在打印功能旁边精确工作。我希望print() 在我输入 p 并按 Enter 时打印节点,但在我之后输入一个字符之前它不会打印。由于我无法弄清楚这一点,您能发现我的错误吗?

print()方法

void print(struct node *root)
{
    if (root != NULL)
    {
        printf("(");
        print(root->left);
        printf("%d", root->data);
        print(root->right);
        printf(")");
    }
}

main()方法

int main(int argc, char** argv)
{
    char input;
    int n;
    char insertt = 'i';
    char printt = 'p';
    char searchh = 's';
    char deletee = 'd';
    
    struct node *root = NULL;
    while(scanf("%c%d", &input, &n) !=-1)
    {
        if(input==insertt)
        {
            root = insert(root,n);
        }
        else if(input==deletee)
        {
            root = deleteNode(root,n);
            
        }
        else if(input==searchh)
        {
            if(search(root,n))
                printf("present\n");
            else printf("absent\n");
        }
        else if(input==printt)
        {   
            print(root);
        }       
    }
    return 0;
}

【问题讨论】:

  • 这能回答你的问题吗? scanf Getting Skipped
  • 尝试将"%c%d" 更改为" %c%d"。阅读重复的帖子以获得更多解释。

标签: c shell debugging terminal


【解决方案1】:

查看代码中while(scanf("%c%d", &input, &n) !=-1 中的 "%c%d"(%c 表示字符输入,%d 表示整数)。您要求输入一个字符,然后输入一个整数。因此,您必须同时提供两个输入,第一个是字符,第二个是整数。

输入字符而不是整数作为第二个输入起作用的原因是,您始终可以为整数输入一个字符,并且 C 编译器将采用其 ascii 值(整数)(尽管我猜这种行为可以在现代编译器中进行控制/修改)。

【讨论】:

  • 我将while循环分成两行,现在我的数据没有被插入
猜你喜欢
  • 2015-05-27
  • 2017-03-25
  • 2014-12-27
  • 2014-12-15
  • 2019-04-17
  • 1970-01-01
  • 2012-05-22
  • 2015-01-27
  • 1970-01-01
相关资源
最近更新 更多