如果用户在结构中输入某个单词,我该如何打破循环?C++
How do I break from a loop if a user enters a certain word into a structure? C++
基本上,程序要求用户输入产品名称,该名称将被输入到结构中。但是,如果输入的名称是"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[]
。
相关文章:
- Python中的for循环与C++有何不同
- 使用输入打破 OpenMP 中的循环
- 打破循环引用在C++中更优雅
- 打破一会儿循环C++
- 纯引用而不是weak_ptr来打破循环依赖关系
- 如何在Arduino中打破循环?
- 当用户输入负数C 时,请打破循环
- C :使用文件末端(CTRL Z)结束一个循环似乎打破了我程序的其余部分
- 如何打破循环以在C 中获取整数数组
- C 如何打破while查找循环
- 无锁单生产者/单消费者循环缓冲区-CPU推测能否打破内存屏障逻辑
- 如何在按键按下C 循环运行,但将其打破每个升降机
- 通过回调功能,打破一个循环的最佳方法是什么?
- C++打破循环包括
- C++ DLL - 打破循环依赖项
- 如果用户在结构中输入某个单词,我该如何打破循环?C++
- 如何通过Enter (c++)打破循环
- 打破循环for循环
- 在这种情况下,是否需要打破循环依赖关系
- 当一个特定的角色被击中时,我该如何打破循环?