【发布时间】:2014-01-07 03:44:46
【问题描述】:
我刚刚开始使用 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())is wrong. 另外,返回的字符串没有理由成为全局变量。 -
注意数据是全局变量,为什么一定要返回呢?你可以在调用函数后在 main 中访问它。
-
@ThomasMatthews:他们做不同的事情。一个结果是布尔值;另一个处于三态比较结果。
-
@user3116554,好吧,一旦你再次调用该函数,它就会改变。如果另一个函数没有预料到,kaboom。多线程的情况更糟。
标签: c++ string function return main