【发布时间】:2018-03-08 22:57:55
【问题描述】:
我有一个任务要我编写一个读取文本文件的程序,然后使用 Ceasar 密码版本输出该文件的修改版本,该版本根据移位量移动用户调用的文件的字符他们输入。例如,如果我的文件读取“hi”并且他们将其移动 1,则它应该读取“ij”。但是当我运行程序时,当我调用 in1 或 out1 时它无法识别,我只是收到一条错误消息。谁能帮我弄清楚我做错了什么或就如何前进提供任何建议?提前谢谢!
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cctype>
using namespace std;
int main()
{
//Declare user variables
int shift, file1chars = 0;
char filename[25];
ifstream in1;
ofstream out1;
do
{
in1.clear(); //clear status flags
//Prompt user to enter name of input file and amount of shift
cout << "Please enter the name of the input file." << endl;
cout << "Filename: ";
cin >> filename;
//Open file name
in1.open(filename);
//Error message if no file
if (!in1)
cout << "That is not a valid file. Try again\n";
} while (!in1);
do
{
out1.clear(); //clear status flags
//prompt user to input out file
cout << "Please enter the name of the output file." << endl;
cout << "Filename: ";
cin >> filename;
out1.open(filename);
//Error message if no file
if (!out1)
cout << "That is not a valid file. Try again\n";
} while (!out1);
//write some code to the input file
in1 >> "hi"
//write the integers in a different order to the output file
out1 << //idk where to go from here to initiate shift
//prompt user to enter shift
cout << "Please intput the shift amount: ";
cin >> shift;
cout << "Processing complete" << endl;
//Call file (?)
//Tell user file input is complete and is now printing statistics
cout << "\nShifted input file Complete. Now printing statistics " << endl;
//Show statistics for file
cout << "\nStatistics for file: " << filename << endl;
cout << "------------------------------------------------";
//Show characters in file and stats before shift
cout << "\n\nTotal # of characters in file: " << file1chars << endl;
cout << "Statistics before shift: " << endl;
//Show file before shift
//Show user stats after shift
cout << "\nStatistics after shift: " << endl;
//File after shift
//Close files
out1.close();
in1.close();
return 0;
}
【问题讨论】:
-
根据您使用的 C++ 版本,您可能需要使用
in1.open(filename.c_str())。 -
你应该在完成后
close流。在您打开的循环中,使用相同的输出流打开多个文件而不关闭它。 -
请尝试修正您的格式 - 您的缩进有点失控。
-
@ThomasMatthews:fstream 类重载了新版本的
open以将class std::string作为其参数,而不是指向字符串的常量指针。 -
in1 >> "hi"尝试从文件中读取数据并将其存储到常量字符数组中。因为数组是常量,所以这不起作用。我怀疑你不想这样做。我可以建议阅读 `std::string` 吗?
标签: c++ file input fstream caesar-cipher