0

Hello All ,This is me again :icon_mrgreen:

I'm Making a programme which tell the user to input the name
of the product he wants to show its Price and Amount ,but i have a problem:

Here's The Code

#include <iostream>
#include <conio.h>
using namespace std;

struct Shop
{
	int Price;
	int Amount;
};

void PrintPrice (Shop Product);
void PrintAmount (Shop Product);

int main()
{
//For Input:
	Shop FI;

//Products:
	Shop Apple;
	Shop Banana;
	Shop Orange;

//Prices:
	Apple.Price = 3;
	Banana.Price = 5;
	Orange.Price = 7;

//Amounts:
	Apple.Amount = 5;
	Banana.Amount = 10;
	Orange.Amount = 15;

//Programme:
	cout << "Enter The Product's Name: ";
	cin >> FI;

	PrintPrice(FI);
	PrintAmount(FI);

//End Of Programme:
	getch();
	return 0;
}

void PrintPrice (Shop Product)
{
	cout << "The Price Is: " << Product.Price <<endl;
}

void PrintAmount (Shop Product)
{
	cout << "The Amount Is: " << Product.Amount;
}

I Know This Is Wrong:

cin >> FI;

so what can it be replaced by?
Hope you got it...

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by 3bdelhakeem
0

The names of your variables go away after compilation, so you can't query them at runtime. Instead of trying to do something magical, why not store a name in your structure and use that? Of course, your program is missing a lot of required logic to make this work. Here's an example of what I think you want to do:

#include <cstddef>
#include <iostream>
#include <string>

using namespace std;

struct Shop
{
  string Name;
  int Price;
  int Amount;
};

void PrintPrice (string name, Shop products[], size_t n );
void PrintAmount ( string name, Shop products[], size_t n );

int main()
{
  Shop products[] = {
    { "Apple", 3, 5 },
    { "Banana", 5, 10 },
    { "Orange", 7, 15 }
  };
  string name;

  cout<<"Enter The Product's Name: ";
  cin>> name;

  PrintPrice ( name, products, 3 );
  PrintAmount ( name, products, 3 );
}

void PrintPrice ( string name, Shop products[], size_t n )
{
  for ( std::size_t i = 0; i < n; i++ ) {
    if ( products[i].Name == name )
      cout<< "The Price Is: "<< products[i].Price <<'\n';
  }
}

void PrintAmount ( string name, Shop products[], size_t n )
{
  for ( std::size_t i = 0; i < n; i++ ) {
    if ( products[i].Name == name )
      cout<< "The Amount Is: "<< products[i].Amount <<'\n';
  }
}

A couple of asides:

>using namespace std;
I strongly recommend you either not use this and qualify namespaces manually, or take care to avoid using directives in the global scope.

>#include <conio.h>
Don't use conio.h unless you have a very good reason to do so, because it kills your code's portability. Pausing the program at the end with getch is not a good reason, by the way.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.