Строка не возвращается к основной функции

0

Я только начал с c++, и это для проекта, над которым я работаю. Проблема в том, что я не могу вернуть строку из SearchFunction в main. Сама функция поиска работает идеально и легко находит и отображает строку, которую она должна найти, но строка temp остается пустой, несмотря на то, что я возвращаю строку из функции поиска. В результате функция DeleteFunction не работает, потому что не передается строка, которую она должна удалить.

Я попытался использовать указатели вместо того, чтобы возвращать значение, но результат тот же. Пожалуйста, помогите мне понять, где я ошибаюсь.

#include<iostream>
#include<stdio.h>
#include<string>
#include<fstream>
using namespace std;

string data,temp;

string SearchFunction(string);                  
void DeleteFunction(string);                    

int main()
{
    int choice=0,choice3=0;
    char yn1;
    string search;

    cout<<"1. Press 1 to delete."<<endl;
    cin>>choice;
    cin.clear();                                        
    cin.ignore(1000,'\n');                              

    if(choice==1)
    {   
        cout<<"Enter RegNo. of record to be deleted: ";
        getline(cin,search);                        
        search="RegNo.: "+ search;                  //Concatenate with "RegNo: " to ensure that the search is done "by RegNo".
        temp=SearchFunction(search);                

        cout<<"1. "<<temp<<"\n\n";
        cout<<temp.length()<<endl;

        cout<<"Are you sure you want to delete the above record of"<<search<<"? Y/N";
        yn1=getchar();
        cin.clear();                                        
        cin.ignore(1000,'\n');                          

        if(!(yn1=='y' || yn1=='Y' || yn1=='n' || yn1=='N'))
        {
            do
            {
                cout<<"Enter 'Y' or 'N': ";
                yn1=getchar();
            }while(!(yn1=='y' || yn1=='Y' || yn1=='n' || yn1=='N'));
        }

        if(yn1=='y' || yn1=='Y')
        {
            DeleteFunction(temp);                   //Call delete function to delete record.
        }
    }
    return 0;
}


string SearchFunction(string search)
{

    int found=0, check=0;                               //Declare and initialize both variables to 0.
    ifstream outfile;                                   //Create object for reading file.

    outfile.open("student.txt");                        //Open file.

    while(!outfile.eof())                               //Continue loop until the end of file.
    {
        found=0, check=0;                               //Initialize both variables to 0 again in anticipation of repititions.

        getline(outfile, data);                         //Input one row from file to string variable data.
        found=data.find(search, found);                 //Search for the search term in string data.
        if(found!=string::npos)                         //If search term found.
        {
            cout<<data<<endl;                           //Display row.
        }
    }
    outfile.close();

    return data;
}

void DeleteFunction(string temp)
{
    string line;
    ifstream in("student.txt");
    if( !in.is_open())
    {
        cout << "Input file failed to open\n";
    }

    ofstream out("temp.txt");

    while( getline(in,line) )
    {
        if(line != temp )
            out << line << "\n";
    }
    in.close();
    out.close();    

    remove("student.txt");
    rename("temp.txt","student.txt");
}
  • 1
    Во-первых, while (!eof()) не так. Кроме того, нет никакой причины для этой возвращаемой строки быть глобальной переменной.
  • 0
    Примечание: данные являются глобальной переменной, почему вы должны ее возвращать? Вы можете просто получить к нему доступ после вызова функции.
Показать ещё 6 комментариев
Теги:
string
function
return
main

2 ответа

1
Лучший ответ

Вы перестали читать файл после того, как нашли строку, которую ищете. Возможно, вы хотите изменить функцию:

string SearchFunction(string search)
{

    int found=0, check=0;                               //Declare and initialize both variables to 0.
    ifstream outfile;                                   //Create object for reading file.

    outfile.open("student.txt");                        //Open file.

    // Also check if found!!!
    while(!outfile.eof() && !found)                     //Continue loop until the end of file.
    {
        found=0, check=0;                               //Initialize both variables to 0 again in anticipation of repititions.

        getline(outfile, data);                         //Input one row from file to string variable data.
        found=data.find(search, found);                 //Search for the search term in string data.
        if(found!=string::npos)                         //If search term found.
        {
            cout<<data<<endl;                           //Display row.
        }
    }
    outfile.close();

    return data;
}
  • 0
    если вы нашли его, зачем продолжать бежать? почему бы просто не вернуться после кута внутрь?
  • 0
    Нет, нет, это то, что вы делаете. И это неправильно. Извините, я имел в виду: «Вы не должны продолжать работать в то время как» Поэтому вы должны проверить в то время как заявление, если найдены становятся правдой. Смотрите код, который я разместил.
Показать ещё 11 комментариев
1

Вы должны выйти из в while цикла, когда вы нашли свои данные. Простой способ - просто return в этот момент.

Не используйте глобалы, если у вас нет очень веских оснований. Глобалы, используемые в качестве переменных с нуля, как указано выше, являются просто Evil .

Ещё вопросы

Сообщество Overcoder
Наверх
Меню