Basically, the program is asking for a user entered product name which will be entered into a structure. However, if the name entered is “quit” (without the quotes) the loop should terminate. Here is the complete code:
#include <iostream>
#define maxNum 9
using namespace std;
struct Products{
char name [20];
int modelNumber;
float price;
} products [maxNum];
void productsDisplay (Products products);
int main()
{
int i;
int k;
cout << "Enter up to 10 product details.\n"
<< "Enter quit as product name to exit the program.\n";
for (i = 0; i <= maxNum; i++)
{
cout << "Enter the product name: ";
cin >> products[i].name;
if (products[i].name == "quit")
break;
cout << "Enter the model number: ";
cin >> products[i].modelNumber;
cout << "Enter the price: ";
cin >> products[i].price;
cout << endl;
}
for (k = 0; k <= i; k++)
{
productsDisplay (products[k]);
}
system("pause");
return 0;
}
void productsDisplay (Products products)
{
cout << "Product name: " << products.name << endl;
cout << "Model number: " << products.modelNumber << endl;
cout << "Product price: $" << products.price << endl;
cout << "----------------------\n";
}
The main problem is this bit:
for (i = 0; i <= maxNum; i++)
{
cout << "Enter the product name: ";
cin >> products[i].name;
if (products[i].name == "quit")
break;
Everything actually works fine except when I enter “quit” the program doesn’t break from the for loop and continues until it is finished. The solution probably lies with using string-type instead and the “strcopy” statement but I’m not too sure how to implement them correctly. I’m quite stumped over this problem and would appreciate any assistance on fixing it, thanks for reading.
The comparison
is wrong.
You need to use
strcmp(orstrncmp, as Vaibhav pointed out):But since this is C++, I suggest you use
std::stringinstead ofchar[].