我对 c++ 相当陌生,是的,这是一项家庭作业。我正在考虑在我的函数中使用 switch 语句而不是 if else 语句。
我正在尝试在处理数据后将从输入文件流读取的信息写入输出文件。
prgram 应该从文件中读取信息,对其进行处理,然后在控制台上显示数据,并将结果写入输出文件,程序应该要求用户输入输入和输出文件的文件名。
我无法让我的程序创建文件。它适用于已经存在的文件。
如果文件不存在,请帮助我让我的程序创建一个文件。
哦,这是在 C++ 中
任何帮助将不胜感激。
我的代码:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;
char getNumber(char l);
int main ()
{
string s1 = "D:\\Unisa\\Assignment_stuffs\\COS1512\\Assignment\\";
string inFile, outFile;
cout << " Please enter the input filename: ";
cin >> inFile;
cout << "\nPlease enter the output filename: ";
cin >> outFile;
string inFileAdd = s1 + inFile;
string inFileAdd2 = s1 + outFile;
ifstream in_stream;
ofstream out_stream;
in_stream.open(inFileAdd.c_str(), ios::in);
if (in_stream.fail())
{
cout << "Error!! Input file opening failed.";
exit(1);
}
out_stream.open(inFileAdd2.c_str(), ios::out);
if (out_stream.fail())
{
cout << "Error!! Output file opening failed.";
exit(1);
}
char next = ' ';
string letter;
while (!in_stream.eof())
{
in_stream.get(next);
while (next != '\n')
{
cout << next;
out_stream.put(next);
letter = letter + getNumber(next);
in_stream.get(next);
}
cout << " " + letter;
out_stream << " " + letter << endl;
letter = "";
cout << endl;
}
in_stream.close();
return 0;
}
char getNumber(char l)
{
if ((l == 'A') || (l == 'a') || (l == 'B') || (l == 'b') || (l == 'C') || (l == 'c'))
{
return '2';
}
else if ((l == 'D') || (l == 'd') || (l == 'E') || (l == 'e') || (l == 'F') || (l == 'f'))
{
return '3';
}
else if ((l == 'G') || (l == 'g') || (l == 'H') || (l == 'h') || (l == 'I') || (l == 'i'))
{
return '4';
}
else if ((l == 'J') || (l == 'j') || (l == 'K') || (l == 'k') || (l == 'L') || (l == 'l'))
{
return '5';
}
else if ((l == 'M') || (l == 'm') || (l == 'N') || (l == 'n') || (l == 'O') || (l == 'o'))
{
return '6';
}
else if ((l == 'P') || (l == 'p') || (l == 'Q') || (l == 'q') || (l == 'R') || (l == 'r') || (l == 'S') || (l == 's'))
{
return '7';
}
else if ((l == 'T') || (l == 't') || (l == 'U') || (l == 'u') || (l == 'V') || (l == 'v'))
{
return '8';
}
else if ((l == 'W') || (l == 'w') || (l == 'X') || (l == 'x') || (l == 'Y') || (l == 'y') || (l == 'Z') || (l == 'z'))
{
return '9';
}
}