killezio
killezio

Reputation: 308

About scanf in C

I´m trying to read a string which size i store previously in a variable L.

So, for example, if the size is 3 characters, then i would read it like this:

fscanf(read,"%.3s",pointer);

BUT in this case i will not know the size of the string, as i said earlier, the size i stored in a variable.

I´ve tried using nothing ( because i have no ideia how to do this). i can´t post this question for some reason if i don´t write this i think so ignore this sentence please, or if you can suggest me what i did wrong go ahead.Then what should i do? how can i change the "3" in "%.3s" to the variable that contains the value?

Upvotes: 0

Views: 70

Answers (2)

Claudio Cortese
Claudio Cortese

Reputation: 1380

You can do that using fgets :

char *fgets(char *s, int size, FILE *stream);

According to man:

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Read‐ ing stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.

Code sample :

#include <stdio.h>

int main(void){

        int length = 0;

        puts("Length of the string : ");
        scanf("%d ", &length);

        char string[length];

        fgets(string,length,stdin);

        puts(string);

return 0;

}

or you can use malloc :

#include <stdio.h>
#include <stdlib.h>

int main(void){

        int length = 0;
        char *string = NULL;

        puts("Length of the string : ");
        scanf("%d ", &length);

        string = malloc((length+1) * sizeof *string);

        fgets(string,length,stdin);

        puts(string);

        free(string);

return 0;

}

Upvotes: 1

Tom Karzes
Tom Karzes

Reputation: 24052

You can dynamically generate the format string that you pass to fscanf. For example:

sprintf(fmt, "%%.%ds", n);

If n is 3, then fmt will contain %.3s for example. You can then pass fmt as the format argument to fscanf. You will need to allocate space for fmt of course, but it should be simple to place an upper bound on the amount of space needed.

Upvotes: 1

Related Questions