0

I am trying to write an unlimited long string input until new line in C. I do not want to waste memory, so I want to dynamically allocate memory for the string. I have a working code, but as soon as I try to put it into a switch case statement it does not work well. I want to loop it and read 5 strings from the user, then put it into a switch case statement, but if I do so, the first iteration of the loop is being skipped. I would appreciate any help or tips.

char* dinput(void){
    size_t m=1;
    char *line=(char*) malloc(m*sizeof(char));
    getline(&line,&m,stdin);
    return line;
}

void new(void) {
    FILE *fp = fopen(file, "a");
    for (int i = 0; i < 5; i++) {
        char *p = dinput();
        fprintf(fp, "%s", p);
        free(p);
    }
    fclose(fp);
}

void menu(void){
    int nav;
    do{
        scanf("%d",&nav);
        switch (nav) {
            case 0:
                break;
            case 1:
                new();
                break;
        }
    }while nav!=0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • How do you put a string into a "switch case"? – Weather Vane Nov 24 '21 at 21:42
  • 1
    Note that `char *arr = (char*) malloc(sizeof(char)*(idx+2));` is allocating a fresh pointer in every loop, and leaving the previous allocation dangling. Did you mean to use `realloc()`? – Weather Vane Nov 24 '21 at 21:44
  • 1
    Uh I see, you seem to to be doing what `realloc` does "by hand". – Weather Vane Nov 24 '21 at 21:45
  • What are you trying to do with a `switch` statement? That aside, as soon as you `return arr`, you're done looping, so you're only going to get one string. You need to save `arr` off somewhere and keep looping if you want 5 strings. – yano Nov 24 '21 at 21:50
  • 1
    POSIX has a `getline` function. – user3386109 Nov 24 '21 at 21:53
  • @user3386109: but not all systems have to implement Posix... – Serge Ballesta Nov 24 '21 at 22:29
  • There is no `switch` in your question. Please [edit] it and show the source that does not work, and please add _why_ it does not work. – the busybee Nov 25 '21 at 10:09
  • I have edited my code, I hope my problem is understandable now. – Beatz_By Dre Nov 25 '21 at 12:06
  • This is a duplicate of [`scanf()` leaves the newline character in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-buffer). I can't VTC because I thought the close reason should be "Needs debugging information" but that's no longer the best close reason. – Jonathan Leffler Dec 01 '21 at 17:11

0 Answers0