How to read the first three characters of a string?

Asked

Viewed 2,396 times

3

I have a C application. It already opens a text file and reads the whole single line that the file has. It’s a long line, for example: Htjxxxxxxxxxxxxxxxxx...

I can store this content of the text file in a variable.

But how do I read the first three characters only?

I need to read only the first three to create a condition that compares them with other values.

In Javascript it would be something like:

if(linha.substr(0, 2) === "HTJ") 
{
    // Condição
}

Thanks in advance!

3 answers

1

You can do it like this:

char *minhastring = "HTJxxxxxxxxxxxxxxxxxxxx"; // string lida no arquivo
char tres_primeiros[4]; // três caracteres mais o terminador de linha
// copia os três primeiros caracteres de um array para o outro
memcpy( tres_primeiros, &minhastring[0], 3); 
tres_primeiros[3] = '\0'; // adiciona o terminador de linha
printf("%s", tres_primeiros); // imprime

See working here.

1

By your question, I believe your intention is just to make the comparison in if and for this case you can use the strncmp function. Then the comparison would look like this:

if(strncmp(linha, "HTJ", 3))
{
    // Condição
}

But if you need to store the first 3 characters in a variable, then the @Marcusvinicius answer is perfect.

0

If you set the array that will save the read string of the file with space to only 3 characters plus the terminator, the function fgets() does so automagically:

char principio[4];
//char resto[1000];
if (!fgets(principio, sizeof principio, ficheiro)) /* erro */;
//if (!fgets(resto, sizeof resto, ficheiro)) /* erro */;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.