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

标签 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;
}


}

最佳答案

我会说错误在这里

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 的流保持关闭状态。

关于c++ - 试图从输入文件中获取字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19208184/

相关文章:

c++ - DX10+ 多顶点缓冲区,单索引缓冲区

c++ - 如何在 C++ 中将 int 转换为二进制字符串表示形式

c++ - GDB C++ 如何停止进入标准库

c++ - C++ Anagram Solver速度优化

c++ - long long 类型在内存中的表示

c++ - 如何测试stringstream运算符>>是否已解析错误类型并跳过它

c++ - 无法将 std::stringstream<char> 转换为 const char*

c++ - "No matching function for call error"与 g++

c++ - 为什么我的方法不从文件 .txt 中读取 float 类型

c++ - 打开 C++ 或 MFC 项目的设置属性页时,如何使 VS2017 匹配配置和平台选择?