如果用户在结构中输入某个单词,我该如何打破循环?C++

How do I break from a loop if a user enters a certain word into a structure? C++

本文关键字:何打破 循环 C++ 单词 结构 用户 输入 如果      更新时间:2023-10-16

基本上,程序要求用户输入产品名称,该名称将被输入到结构中。但是,如果输入的名称是"quit"(不带引号),则循环应终止。这是完整的代码:

#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";
} 

主要问题是这一点:

 for (i = 0; i <= maxNum; i++)
             {
                  cout << "Enter the product name: ";
                  cin >> products[i].name;
                  if (products[i].name == "quit")
                     break;

实际上一切都很好,除了当我输入"退出"时,程序不会从for循环中断,并一直持续到它完成。解决方案可能在于使用字符串类型和"strcopy"语句,但我不太确定如何正确实现它们。我对这个问题很困惑,如果有任何帮助,我将不胜感激,谢谢阅读。

比较

products[i].name == "quit"

是错误的。

你需要使用strcmp(或strncmp,正如Vaibhav所指出的):

if ( strcmp(products[i].name,"quit") == 0 ) //0 indicates equality
      break;

但由于这是C++,我建议您使用std::string而不是char[]