如果用户在结构中输入某个单词,如何从循环中中断?C ++ [英] How do I break from a loop if a user enters a certain word into a structure? C++

查看:63
本文介绍了如果用户在结构中输入某个单词,如何从循环中中断?C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

主要问题是这个位:

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

一切正常,除非我输入退出",程序不会从for循环中中断并继续直到完成.解决方案可能在于改用字符串类型和"strcopy"语句,但我不太确定如何正确实现它们.对于这个问题,我感到很困惑,感谢您提供的修复帮助.

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.

推荐答案

比较

products[i].name == "quit"

错了.

您需要使用 strcmp (或Vaibhav指出的 strncmp ):

You need to use strcmp (or strncmp, as Vaibhav pointed out):

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

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

But since this is C++, I suggest you use std::string instead of char[].

这篇关于如果用户在结构中输入某个单词,如何从循环中中断?C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆