Diogo Carvalho
Diogo Carvalho

Reputation: 255

Scan strings into array in C

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!

Upvotes: 2

Views: 973

Answers (1)

user2736738
user2736738

Reputation: 30906

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.

Upvotes: 1

Related Questions