How to write a string variable without breaking the line?

Asked

Viewed 212 times

1

I need to write only in the first line of a file, but whenever I add a string type variable this line is broken, follow the example:

#include <stdio.h>
#include <string.h>


char name1[10];
char name2[10];
char name3[10];
char name4[10];
FILE *file;

int main(){
    printf("Nome1:");
    fgets(name1, 11, stdin);
    printf("Nome2:");
    fgets(name2, 11, stdin);
    printf("Nome3:");
    fgets(name3, 11, stdin);
    printf("Nome4:");
    fgets(name4, 11, stdin);
    file = fopen("Test.ini","a");//não pode destruir as infos ja adicionadas
    fprintf(file,"Nomes:%s,%s,%s,%s",name1,name2,name3,name4);//<- Erro aqui?
    fclose(file);
    return 0;
}

result in Test.ini file:

Nomes:nome1
,nome2
,nome3
,nome4

As it should be written in the Test.ini file:

Nomes:nome1,nome2,nome3,nome4
  • Attention to buffer overflow: com char name1[10]; what you should use is fgets(name1, 10, stdin); -- I usually use fgets(name1, sizeof name1, stdin); so if I change the size, I don’t need to change two lines of code.

1 answer

1


The fgets() picks up the ENTER you typed and that’s what’s breaking the line. Then in each variable you have to put a terminator in place of this character, one of them:

name1[strcspn(name1, "\n")] = 0;

I put in the Github for future reference.

  • Thanks so much for the help!! It worked here =D

Browser other questions tagged

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