2

I want to scan these values to an array. I created a struct and the array is of that type. My problem is that, when i compile, all the ints work fine, but when it comes to the strings it doesn't let me insert any values and jumps to the next instruction of my code. What am I doing wrong?

printf("\nInsert id: ");
scanf("%i", &vDisp[MAXDISP].idComp);
printf("\nInsert serial number: ");
scanf("%i", &vDisp[MAXDISP].serial);
printf("\nInsert production year: ");
scanf("%i", &vDisp[MAXDISP].year);

printf("\nInsert brand: ");
scanf("%[^\n]%*c", &vDisp[MAXDISP].brand);
printf("\nInsert type: ");
scanf("%[^\n]%*c", &vDisp[MAXDISP].type);
printf("\nInsert model: ");
scanf("%[^\n]%*c", &vDisp[MAXDISP].model);
printf("\nInsert OS: ");
scanf("%[^\n]%*c", &vDisp[MAXDISP].system);

Thanks in advance!

Barmar
  • 741,623
  • 53
  • 500
  • 612
Diogo Carvalho
  • 255
  • 1
  • 7
  • 15
  • Are all those vDisp.XXX are string typed? A little more code would be helpful because MAXDISP could be out of bounds, since your working with a referece &Array, it may be causing the problem. – Fernando Pérez Dec 27 '16 at 15:44
  • Possible duplicate of [input string through scanf](http://stackoverflow.com/questions/782136/input-string-through-scanf) – Margaret Bloom Dec 27 '16 at 15:45
  • 1
    What's the value of `MAXDISP`, and how does it relate to the size of the array? – Barmar Dec 27 '16 at 16:46
  • @user3121023 Note that with `scanf(" %[^\n]%*c", &vDisp[MAXDISP].brand);` it does not allow a user to enter an empty line. User can type `` repeatedly without the function returning. – chux - Reinstate Monica Dec 27 '16 at 19:26
  • MAXDISP value is 20. But that's supposed to limit the number of values in the array, right? – Diogo Carvalho Dec 27 '16 at 19:48

1 Answers1

1

What about scanf("%s",str) ? where str is a char array.

Here is the custom getline function

char * getline(char cp) {
    char * line = malloc(100), * linep = line;
    size_t lenmax = 100, len = lenmax;
    int c;


    if(line == NULL)
        return NULL;

    for(;;) {
        c = fgetc(stdin);
        if(c == EOF)
            break;

        if(--len == 0) {
            len = lenmax;
            intptr_t diff = line - linep;
            char * linen = realloc(linep, lenmax *= 2);

            if(linen == NULL) {
                free(linep);
                return NULL;
            }
            line = linen + diff;
            linep = linen;
        }

        if((*line++ = c) == cp)
            break;
    }
    *line = '\0';
    return linep;
}

cp is the character upto which you wanna read at a line.

user2736738
  • 30,591
  • 5
  • 42
  • 56