在 c++ 中搜索.txt文件只会得到第一行
Search in .txt file in c++ only get's the first line
我有一些房间预订程序,所以我想在.txt文件中搜索,这样我就可以找到预先预订的房间。
问题是:
搜索函数只读取.txt文件中的第一行所以当我输入重复的信息时,它只检查第一行
你能帮我吗谢谢
int search(int search_num){
string search= to_string(search_num);
int offset;
string line ;
ifstream myfile;
myfile.open("booked.txt", ios::app);
ofstream booked ("booked.txt", ios ::app);
if(myfile.is_open())
{
while(!myfile.eof())
{
getline(myfile,line);
if((offset=line.find(search,0))!=string :: npos)
{
return 1;
}
else {
return 2;
}
}
myfile.close();
}
else
cout <<"Couldn't open" << endl;
}
在if语句的两种情况下都返回一个值,从而结束函数的执行。返回一个值将结束函数的执行,因此您总是在读取第一行之后结束。我的猜测是,你想把return 2;
移到函数的末尾。
请注意,通过这种方式,您也总是return
,而从不调用myfile.close()
,这可能会在其他地方引起问题。虽然我不理解您的返回值1和2的含义,但我建议这样做:
int search(int search_num){
string search= to_string(search_num);
int offset;
string line ;
ifstream myfile;
myfile.open("booked.txt", ios::app);
int return_value = 2;
ofstream booked ("booked.txt", ios ::app);
if(myfile.is_open()) {
while(!myfile.eof()) {
getline(myfile,line);
if((offset=line.find(search,0))!=string :: npos) {
return_value = 1;
break;
}
}
myfile.close();
} else {
cout <<"Couldn't open" << endl;
}
return return_value;
}
相关文章:
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 从C++dll访问C#中的一行主要参数
- 在C++中,我如何接受不同于同一行的用户输入
- 如何从一行中读取特定数量的字符?(C++)
- 读取最后一行代码算法 - c++ 时出现问题
- 查找矩阵C++中每一列和每一行的最小和最大元素
- 有没有办法在一行中填充矢量图
- 需要将一行代码从C++ Qt翻译成PyQt
- 为什么如果我添加这一行,我的程序会不断询问值
- 如何使代码打印文本文件中的第一行?
- 如何在C++中以这种方式返回一行文本?
- 如何使用运算符在同一行中多次调用函数
- 如何格式化我的文本文件以使其不会一遍又一遍地重复同一行?
- 而(!inputfile.eof())只读取第一行?
- 这段代码的最后一行在做什么?
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- C++找出覆盖同一行的数组
- 如何让字符数组在一行而不是多行中打印出来?