在 c++ 上搜索结构中的对象
Searching an object inside of struct on c++
我正在为一个可以插入一本书的图书馆制作一个程序,显示所有插入的书,并根据用户插入的book_code搜索一个特殊的书名,我已经完成了其中的 2 个,但最后一个(搜索(不会按预期运行..如果这里有人可以帮助我,我将不胜感激。这是代码
#include <iostream>
#include <conio.h>
void show_book(const Book &book );
void input_book (Book &book);
int main ()
{
Book book[10];
int i,x;
char search;
int position,found;
cout<<"How many book you want to add = "; cin>>x;
for (i=0; i<x; i++){
input_book(book[i]);
}
for(i=0; i<x; i++){
show_book(book[i]);
}
//this is my searching code , im stuck here ..
cout<<"n====== SEARCH ====="<<endl;
cout <<"Enter book code = "; cin>>search;
for (i=0; i<x; i++){
if(book->book_code[i] == search){
found = 1;
position = i;
i = x;
}
}
if (found != 0){
show_book(book[position]);
} else{
cout<<"The book is not exist";
}
return 0;
}
//function declaration...
void show_book(const Book &book){
cout<<book.book_code<<" | "<<book.book_title<<endl;
}
void input_book(Book &book){
cout << "Book code : ";cin >> book.book_code;
cin.ignore(1, 'n');
cout << "Book title : " ;getline(cin, book.book_title);
}
这是现在的输出看起来像
found
在搜索块开始时未初始化为 0。
修订后的代码如下
for (i=0,found=0;i<x && !found; ++i)
if (book[i].book_code == search)
{
found = 1;
position = i;
}
你应该改变
if(book->book_code[i] == search) // accesses 1-st book, namely book[0]
自
if(book[i].book_code == search) // accesses i-th book
如果你可以使用std::array
,那就更好了,而不是Book book[10];
你可以写:
std::array<Book, 10> book;
并在他的评论中指出弗兰克,对于search
,您应该使用与book_code
相同的类型.
此外,最好对变量使用bool
found
:
bool found = false;
相关文章:
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 具有引用成员的结构是否具有唯一的对象表示形式
- 为什么我们再次从结构对象创建结构变量?
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- C++:对象将 lambda 存储到结构中,稍后调用该函数
- 如何在C++中表示JSON文档的递归对象结构?
- 哪些值存储在对齐的结构/类对象的填充字节中
- 结构对象的指针成员在传递给函数时被修改
- C++ 提升 - 包含类层次结构对象的类的序列化
- 在 c++ 中使用字符串变量选择静态类结构,而不带对象
- 如何通过不同的指针使用类的对象访问结构?(链表)(C++)
- 是否可以在C++ (C) 中使用全局范围对象(结构)?
- 将数组/对象/结构列表从C#库中传递给C MFC应用程序
- 如何使用方法返回指向对象结构的指针?
- 对象/结构等的C++内存布局是什么?
- 这些不同的对象结构之间有什么区别
- 如何找到C++可执行文件的所有对象(类对象/结构)
- C/C++ 中的对象/结构对齐
- 额外的继承对对象结构或实例化有影响吗?
- 尝试处理嵌套对象/结构和动态数组时出现内存泄漏或内存错误。可能的 Xcode/malloc 问题