Anis AIT
Anis AIT

Reputation: 41

Scanf() a sentence which contains spacebar character

I'm trying to store a string from the user's inpute ( with scanf()) in a .txt file by using open(), write(). I do use a buffer to store the input, then send it to the file with write(). The problem is that i can't store any " " which is a spacebar's character... It does only store the characters before the space. But i actually want to keep writing until the '\n'. here's my code :

 void writing(char* argument){
    int desc_fich=-1, nb_lus=-1, nb_write=-1;
    
    printf("Enter the words : ");

        char entry[50];

        for (int i=0;i<50; i++){
            entry[i]= '\0'; 
        }

        scanf("%s", &entry);

        int i=0;
        int number=0;

        while ( entry[i] != '\0' ){

            number++;
            i++;
        }

        desc_fich = open(argument, O_WRONLY | O_CREAT | O_APPEND);

        nb_write = write(desc_fich, entry, nombre); 


        close(desc_fich);
}

`

Upvotes: 0

Views: 353

Answers (1)

chux
chux

Reputation: 154335

scanf("%s", &entry); first reads and skips over all leading white-space. Then reads and saves, perhaps too many, non white-space characters.

Instead of scanf(), use fgets() to read a line.

   // scanf("%s", &entry);
   if (fgets(entry, sizeof entry, stdin)) {
     ...
     // nb_write = write(desc_fich, entry, nombre);
     nb_write = write(desc_fich, entry, strlen(entry));

Upvotes: 2

Related Questions