Function getchar () reads only the first letter

-3
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
FILE *fd;
void agregar(int nombre_articulo, char direccion[]);
int main()
{
    int respuesta, c;
    int nombre_articulo;
    char direccion[] = "C:\Users\ploo\OneDrive\Escritorio\datos_inventario\pelis.txt";

    while(respuesta!=3)
    {
        printf("\n\tINVENTARIO\n1.Revisar inventario\n2.Agregar articulo\n3.Salir\n");
        scanf("%i", &respuesta);
        switch(respuesta)
        {
            case 1:
                fd=fopen(direccion,"rt");
                if(fd==NULL)
                {
                    printf("ERROR");
                    return 1;
                }
                while((c=fgetc(fd))!=EOF){
                    if (c=='\n')
                    {
                        printf("\n");
                    }
                    else
                    {
                        putchar(c);
                    };
            } fclose(fd);break;

            case 2:
                agregar(nombre_articulo, direccion);break;

        }
    }
    return 0;
}
void agregar(int nombre_articulo, char direccion[]){
    int respuesta;
    while (respuesta !=2)
    {

        while((nombre_articulo = getchar()) != EOF && nombre_articulo != '\n')
        {
        printf("Cual es el nombre del articulo que se desea agregar?\n");
        fflush(stdin);
        printf("\nEs %s el nombre correcto?\n", &nombre_articulo);
        fflush(stdin);
        printf("\n1.Si\t\t\t2.No\n");
        scanf("%i", &respuesta);
        if (respuesta== 1)
        {
            fd=fopen(direccion, "wt");
            if (fd==NULL){
                printf("ERROR");
            }
            fprintf(fd,"\n");
            fwrite(nombre_articulo,1,strlen(nombre_articulo),fd);
            respuesta = 2;
            fclose(fd);

        }
    }
        }

}
    
asked by plk 03.01.2019 в 17:48
source

1 answer

1

I think the name of the function is obvious enough. getchar only reads a character . If you read a string the logical thing would then be that it had a name of type getstring or getline or similar.

To read a string you do not need a int but an array of char :

int nombre_articulo; // <<--- Quita esto
char cadena[100]; // Por ejemplo

And, in second place, you need to use a function that reads text strings:

scanf("%s",cadena); // Si no quieres leer espacios

getline(cadena, 100, stdin); // Si quieres leer la linea entera
    
answered by 04.01.2019 в 10:39