#weird behaviour string

27 messages · Page 1 of 1 (latest)

lucid valve
#
int main()
{
    char content[255];
    char strings[3][255];
    FILE *file = fopen("test.txt", "r");

    if (file == NULL)
    {
        printf("Couldnt open the file");
    }
    int counter = 0;
    while (!feof(file))
    {

        fgets(content, 15, file);
        printf("%s", content);
        strncpy(strings[counter], content, sizeof(content));
        counter++;
    }

    for (int i = 0; i < 3; i++)
    {
        printf("%s\n", strings[i]);
    }
}

I basically just want to read from a file lines of string and cope them into an array of strings.

When i print them something weird happens

The first line printed is separated by a newline
the last one is cut off

burnt brambleBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

pliant wharf
#

The first line printed is separated by a newline
thats because fgets() also includes the newline in the string
the last one is cut off
thats because you only read 15 characters max

lucid valve
#

oh thanks

#

another question

#

if i define strings like this

#

"Dasdasd"

#

the null terminator is included

pliant wharf
#

yes

neat meteor
#

That's a statement. Not a question.

pliant wharf
#

lol

neat meteor
#

A correct one, at that.

pliant wharf
#
char s1[] = "";
// same as 
char s2[] = {'\0'};

char s3[] = "lol";
// not the same as
char s2[] = {'l', 'o', 'l'};
burnt brambleBOT
#

@lucid valve Has your question been resolved? If so, type !solved :)

lucid valve
#
char s3[] = "lol";
char s2[] = ['l', 'o', 'l', '\0'}
pliant wharf
#

yes if you replace the second [ with {

#

this is C, not python or JS

lucid valve
#

trie

#

true sorry

#

xD

#

but it would be better to initialize the

#

arrays dynamicall right?

lucid valve
#

!closed

neat meteor
lucid valve
#

!solved

burnt brambleBOT
#

Thank you and let us know if you have any more questions!

This thread is now set to auto-hide after an hour of inactivity

lucid valve
#

!solved