简体   繁体   中英

fgets doesn't wait for user input in my C code

I'm trying to do a simple code to write some stuff on a .csv file. I wrote a for loop and a bunch of fgets() to get the data from the file, but the program doesn't wait for the user to input the info and just closes the program. Does anyone have any idea on how to fix it?

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

#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)

int main() {
    setlocale(LC_ALL, "Portuguese");

    int i;
    char nome, tel, email, cpf;
    FILE *f_ptr;
    f_ptr = fopen("3556346.csv", "w+");     
    fprintf(f_ptr, "Nome, CPF, Telefone, E-mail\n");        
    
    for (i = 0; i < 6; i++) {
        printf("Digite o nome: ");
        fgets(&nome, sizeof(nome), stdin);
        printf("Digite o CPF: ");
        fgets(&cpf, sizeof(cpf), stdin);
        printf("Digite o telefone: ");
        fgets(&tel, sizeof(tel), stdin);
        printf("Digite o e-mail: ");
        fgets(&email, sizeof(email), stdin);
        fprintf(f_ptr, "%c, %d, %c, %c\n", nome, cpf, tel, email);
    }       
    fclose(f_ptr);

    return 0;
}

PS: If anyone came here with the same problem as I had. The solution, like the nice people below pointed out, it to put [101] after the name of each char declaration. Like char nome[101] , tel[101] , ... Also in the fprintf command, you should use %s instead of %c . And one last thing I found out, fgets stores a break line, so if you don't want it, you need to write nome[strcspn(nome, "\n")] = '\0'; after each fgets , where nome is the name of the variable.

The fgets() function reads at most one less than the number of characters specified by size from the given stream and stores them in the string str.

Since all your variables are single characters, you're asking fgets for single byte. It reads one less, to keep room for a termimating mull byte, which is zero.

fgets reads strings not characters. You need to store it in a string, not a character. If you want to store just one character, allocate two bytes. One for the character, one for the terminating null byte.

char nome[2];
fgets(nome, sizeof(nome), stdin);

But I suspect you want to store more than one character. You have to allocate enough memory, plus one.

// enough memory for 100 characters, pus the terminating null byte.
char nome[101];
fgets(nome, sizeof(nome), stdin);

Or, better yet, allocate a single large buffer and copy it into a properly sized amount of memory.

char line[4096];
printf("Digite o nome: ");
fgets(line, sizeof(line), stdin);
char *nome = strdup(line);

printf("Digite o CPF: ");
fgets(line, sizeof(line), stdin);
char *cpf = strdup(cpf);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM