简体   繁体   English

在c ++中搜索.txt文件只得到第一行

[英]Search in .txt file in c++ only get's the first line

I got some sort of room reservation program so i wanna search in .txt file so i can find the pre reserved rooms . 我有一些房间预订程序所以我想搜索.txt文件,所以我可以找到预留的房间。

the Problem is: 问题是:

The search function only reads the first line in the .txt file so when i enter a duplicated information it checks only the first line 搜索功能只读取.txt文件中的第一行,因此当我输入重复的信息时,它只检查第一行
can u help me out with it Thanks 你可以帮帮我吗谢谢

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;

} }

You are ending the execution of the function by returning a value in both cases of the if statement. 您将通过在if语句的两种情况下返回值来结束函数的执行。 Returning a value will end the execution of the function, so you always end after reading the first line. 返回一个值将结束函数的执行,因此您总是在读完第一行后结束。 My guess is you want to move the return 2; 我的猜测是你想要return 2; to the very end of your function. 到你的功能的最后。

Note that this way you also always return without ever calling myfile.close() which might cause problems elsewhere. 请注意,通过这种方式,您始终可以return而不会调用myfile.close() ,这可能会导致其他地方出现问题。 While I don't understand the meaning of your return values 1 and 2, I suggest this: 虽然我不明白你的返回值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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM