Как правильно использовать scanf для правильного сканирования членов структуры?В настоящее время я перезаписываю цену и количество на имя - PullRequest
0 голосов
/ 03 февраля 2019

У меня проблема с функцией чтения элемента.Когда я использую scanf, я неправильно сканирую нужный элемент структуры.Когда я использовал свой отладчик, я вижу неправильные числа в полях количества и цены.Идея состоит в том, что я хотел бы иметь возможность принять название продукта, которое может включать пробелы, затем отсканировать цену и отсканировать сумму.

Примерно так:

scanf ("% 63[^ \ n] s% f% u ", productName, & (myItems-> fPrice), & (myItems-> iQuantity));

IDE: Компилятор Netbeans: ОС Cygwin: Windows 7 64bit

  enter code here

    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */

    /* 
     * File:   main.c
     * Author: Armando Valencia
     *
     * Created on February 2, 2019, 3:05 PM
     */

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define STRING_LENGTH 64
    /*
     * C program that creates a structure pointer and passes it to func
     * if you define the stuct outside main you are not allocating any memory for it
     */

    typedef struct Item{
        char *pItemName;
        unsigned int iQuantity;
        float fPrice;
        float fAmount;
    }sItem;

    void readItem(sItem *myItems);
    void printfItem(sItem *myItems);

    int main(int argc, char** argv) {
        sItem sPurchase;
        sItem *psItems = &sPurchase;
        readItem(psItems);
        printfItem(psItems);

        return (EXIT_SUCCESS);
    }

    /*
     * Create a function named readItem that takes a structure pointer
     * of type item as a parameter. This function should read in 
     * (from the user) a product name, price, and quantity
     *  the contents be stored in the passed in structure to the
     *  function 
     */
    void readItem(sItem *myItems){
        char productName[STRING_LENGTH] = {0};
        printf("Enter the name of your product, the price and quantity: ");
        scanf("%63[^\n]s %f %u", productName, &(myItems->fPrice), &(myItems->iQuantity));
        productName[STRING_LENGTH-1] = '\0';
        //allocate memory to hold name
        myItems->pItemName = (char *) calloc(strlen(productName) + 1, sizeof(char));

        //copy name to allocated memory
        strncpy(myItems->pItemName, productName, strlen(productName));

        //calculate amount
        myItems->fAmount = myItems->iQuantity * myItems->fPrice;
        return;
    }

    void printfItem(sItem *myItems){
        printf("Purchase information\n");
        printf("Item name: %s\nQuantity: %u\nPrice: %.2f\nTotal amount: %.2f\n",
                myItems->pItemName, myItems->iQuantity, myItems->fPrice, myItems->fAmount);
    }
...