[英]Using I/O streams to read from one file and write to another
我正在阅读一本教科书,其中的练习需要从一个文件中复制文本,并将其写成与另一文件小写等效。 我似乎找不到仅使用I / O流来做到这一点的方法(我在网上找到的大多数解决方案都使用流缓冲区)。
我的代码是这样
int main()
{
string f_name1, f_name2;
cout << "enter the file names" << '\n';
cin >> f_name1>>f_name2;
ofstream fs{ f_name1 };
ifstream fsi{f_name1};
ofstream fs2{f_name2};
fs << "LoRem ipSUM teXt TaXi";
char ch;
while (fsi.get(ch)) {
fs2 << ch;
}
运行后,没有任何内容写入第二个文件(f_name2)。 这只是一个空白文件。
编辑:
这也不起作用
int main()
{
string f_name1, f_name2;
cout << "enter the file names" << '\n';
cin >> f_name1>>f_name2;
ofstream fs{ f_name1 };
ifstream fsi{f_name1};
ofstream fs2{f_name2};
fs << "LoRem ipSUM teXt TaXi";
char ch;
while (fsi>>ch) {
fs2 << ch;
}
}
您正在使任务复杂化,而没有明显的收获。 不需要
ofstream fs{ f_name1 }; fs << "LoRem ipSUM teXt TaXi";
使用文本编辑器并在程序外部创建输入文件的内容。
这是您的main
功能的更新版本:
int main()
{
string f_name1, f_name2;
cout << "enter the file names" << '\n';
cin >> f_name1 >> f_name2;
ifstream fs1{f_name1};
if ( !fs1 )
{
std::cerr << "Unable to open " << f_name1 << " to read from.\n";
return EXIT_FAILURE;
}
ofstream fs2{f_name2};
if ( !fs2 )
{
std::cerr << "Unable to open " << f_name2 << " to write to.\n";
return EXIT_FAILURE;
}
// Using ostream::put() seems the right function to use
// for writing when you are using istream::getc() for reading.
char ch;
while (fs1.get(ch))
{
fs2.put(std::tolower(ch));
}
}
嗯。 因此,您正在写入文件,然后读取内容并再次写出。 好的...
您可能需要在fs <<代码之后输入fs.flush()。 可以对数据进行缓冲,等待换行符触发刷新,或者自己进行操作。
我还将在while循环中放入一些打印语句,以确保您得到的是您想得到的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.