Я только что начал с 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");
}
Во-первых, ['while (! Eof())' неверно.] (Http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) Кроме того, нет никакой причины, чтобы возвращаемая строка была глобальной переменной. – chris
Данные примечания - это глобальная переменная, почему вы должны ее вернуть? вы можете просто получить доступ к нему в основном после вызова функции. –
Почему? [при использовании операторов сравнения в строке все делается под функцией сравнения] (http://en.cppreference.com/w/cpp/string/basic_string/operator_cmp). – Johan