【发布时间】:2022-11-27 10:41:45
【问题描述】:
目前正在制作一个记录系统,它将继续添加记录,直到我输入“99”。但是,即使我输入“99”,它仍会继续运行系统。
为了更好地说明这是我的代码的样子:
#include <cstdio>
#include <string>
#include <iostream>
using namespace std;
struct book {
char authorName[100], titleName[100], pubName[100];
float price;
int stockNum;
}list;
int choice;
int main() {
for (;;) {
cout << "Enter Author Name :";
cin.ignore();
cin.getline(list.authorName, 100);
if (list.authorName == "99") {
break;
}
cout << "Enter Title Name :";
cin.getline(list.titleName, 100);
cout << "Enter Publisher Name:";
cin.getline(list.pubName, 100);
cout << "Enter Price in RM :";
cin.ignore();
cin >> list.price;
cout << "Enter Stock Position :";
cin >> list.stockNum;
cout << "Record Saved!" << endl;
}
return 0;
}
我尝试将其更改为其他循环(while 循环)。 我尝试将 cin.getline 更改为 cin。 即使尝试将输入更改为 char (NO,STOP) 也不会影响循环
【问题讨论】:
-
在调试器中运行您的代码并查看变量。
-
struct book { ... } list;在语义上没有意义。一本书不是清单。对于编译器来说,它在语法上是有意义的,你现在有一本名为 list 的书。 -
另请注意,您会收到编译器警告:
comparison with string literal results in unspecified behavior。不要在 C++ 中使用char[],只能使用std::string。 -
包括
cstring,并将您的条件替换为if (strcmp(book.authorName, "99") == 0)。 -
@RohanBari 或者只使用已经包含的
std::string并继续使用operator==
标签: c++ for-loop break dev-c++