试图从输入文件中获取字符

时间:2013-10-06 11:08:51

标签: c++

我正在尝试从输入文件中获取字符,但我无法让它工作,任何可以帮助我的人都可以使用它?我提前为格式化道歉,这让我很困惑。

open_input_and_output_file基本上检查你是否可以打开文件,而在OTP中我试图将每个字符从一个文件转移到另一个文件。由于我无法让它工作,我首先尝试在控制台应用程序中显示这些字符,但这也无效。

任何帮助都将不胜感激,我希望所提供的信息足够。

    bool open_input_and_output_file(ifstream& infile, ofstream& outfile)
{
//Precondition: True
assert(true);
//Postcondition: Inputfile and outputfile have either been opened succesfully or you have been notified of it not opening succesfully.
string inputfile;
string outputfile;
cout<<"\nPlease enter an input-file name (no spaces): ";
cin>>inputfile;
cout<<"NOTE: Input-file name and output-file name can NOT be the same!"<<endl;
cout<<"Please enter an output-file name (no spaces): ";
cin>>outputfile;
if(inputfile != outputfile)
{
    cout<<"Input-file name and output-file name are not the same! Good job on reading!"<<endl;
    ifstream infile(inputfile.c_str());
    if(infile)
        cout<<"Input-file: "<<inputfile<<" was opened succesfully!"<<endl;
    if(!infile)
        cout<<"Inputfile: "<<inputfile<<" could not be opened!"<<endl;
    ofstream outfile(outputfile.c_str());
    if(outfile)
        cout<<"Output-file: "<<outputfile<<" was opened succesfully!"<<endl;
    if(!outfile)
        cout<<"Outputfile: "<<outputfile<<" could not be opened!"<<endl;
}

else
{
    cout<<"Input-file name and output-file name are the same!"<<endl;
    cout<<"Opening has failed!"<<endl;
}
return 0;
}
void OTP(ifstream& infile, ofstream& outfile)
{
int choice;
char character;
unsigned int r;
srand(r);

cout<<"\nPlease enter 0 to encrypt or 1 to decrypt: ";
cin>>choice;
if(open_input_and_output_file(infile,outfile))
{
    infile.get(character);
    cout<<character;
}


}

1 个答案:

答案 0 :(得分:0)

我会说错误就在这里

cout<<"Input-file name and output-file name are not the same! Good job on reading!"<<endl;
ifstream infile(inputfile.c_str());

应该是

cout<<"Input-file name and output-file name are not the same! Good job on reading!"<<endl;
infile.open(inputfile.c_str());

你用outfile犯了同样的错误。

ofstream outfile(outputfile.c_str());

应该是

outfile.open(outputfile.c_str());

您将infile和outfile作为参数传递给open_input_and_output_file函数,但随后在函数内再次声明它们 。因此,当您打开文件时,您没有使用传递给open_input_and_output_file的流,而是使用该函数本地的流。传递给open_input_and_output_file的溪流保持关闭状态。