Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Reading a string & int from stdin (or redirect from file)

First-time poster to Stack Overflow, cheers to anyone who can help.

Having trouble with my main program, which should "read from stdin (or redirect from a file) pairs of string and integer (string followed by int, one pair per line) and insert these pairs, in the order they are read, into an initially empty binary search tree."

Having tested the binary search tree insertion & traversal itself using a test case provided, I know my insertion & traversal work. However, I'm struggling to read in the string & int together on the same line, and am unsure how to implement the file redirection (can I just use a cat command on the UNIX server I'm uploading it to?).

Here's my 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);
}

I tried to use a while loop with a scanf condition == 2 to test if both the string and int were correctly read, but my implementation is wrong (program crashes upon reaching the while loop).

Am I completely on the wrong track here? Or is there a logical error that I'm just flat out missing? Thanks again!

like image 702
kapkong Avatar asked Oct 18 '22 15:10

kapkong


1 Answers

You need to allocate memory for str, try char str[256] instead of char * str.

Also remove the scanf from the bottom of the while loop, it's not necessary.

like image 88
cleblanc Avatar answered Oct 21 '22 07:10

cleblanc