将文件读入程序
Reading files into program
我正在尝试编写一个程序:-读取文本文件,然后将其放入字符串中-通过减去 4 来更改字符串中的每个字母-输出更改的行
我了解如何输入/输出文件。我没有比这更多的代码,而且相当卡住,因为这对我来说是一个非常新的概念。我已经研究过,但找不到直接的答案。如何将原始文件的每一行输入到一个字符串中,然后对其进行修改?
谢谢!
// Lab 10
// programmed by Elijah
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
fstream dataFile;
//Set the file "coded" as the line input
dataFile.open("coded.txt", ios::in);
//Create the file "plain2" as program output
dataFile.open("plain2.txt", ios::out);
}
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile ("coded.txt"); //explicitly input using ifstream rather than fstream
ofstream outFile ("plain2.txt"); //explicitly output using ofstream rather than fstream
string str = "";
char ch;
while (inFile.get(ch))
{
if (ch!='n' && ch!=' ')
{
//do your manipulation stuff //manipulate the string one character at a time as the characters are added
}str.push_back(ch); //treat the string as an array or vector and use push_back(ch) to append ch to str
}
}
这会更明确地打开输入和输出文件流,然后创建一个空字符串和单元化字符。 inFile.get(ch)
将返回 true,只要它不在文件的末尾,并将下一个字符分配给 ch
。然后在循环中,您可以对ch
执行任何需要执行的操作。我只是将其附加到字符串中,但听起来您会想在附加之前做点什么。
在您的情况下,get(ch) 将比 getline() 或>> 方法更好,因为 get(ch) 还将添加空格、制表符和其他特殊字符,这些字符是 getline() 和>> 将忽略的文件的一部分。
如果 string-4 是指操作行中少 4 个字符,则可以使用:
ch = ch-4;
请注意,如果 ch 最初是"a"、"b"、"c"或"d",这可能会产生与您预期的结果不同的结果。如果要环绕,请使用 ascii 操作和模运算符 (%)。
您正在覆盖 dataFile,因此您必须创建第二个fstream
或先处理字符串,然后使用相同的fstream
进行输出。
字符串读取:
http://www.cplusplus.com/reference/string/string/getline/字符串修改:
http://www.cplusplus.com/reference/string/string/replace/"字符串 - 4"是什么意思?
- make 命令创建 .file,但不创建应用程序文件
- C++对象文件和程序文件组合编译的 Bashrc 别名
- 程序文件中的安装路径:一些问题
- 词频程序 - 文件输入太大?
- 使用带有 MEX 包装器的帮助程序 C 文件从 MATLAB 2016 调用C++代码时出现问题
- 如何修复"无法打开包含文件'boost/config.hpp':没有这样的文件或目录(包括目录涵盖:C:\程序文件\boost\boost_1_67_0)
- MacOS应用程序文件关联
- Visual Studio - C++ - 以 32 位或 64 位构建和运行应用程序 - 从适当的程序文件目录加载 D
- Windows 8 应用商店应用程序C++文件访问
- 检索C++程序/文件中使用的指针变量列表
- Visual Studio使用多线程DLL发布应用程序文件
- 为什么不将.cpp转换为c程序文件呢
- C++获取程序文件目录,附加额外路径并执行
- C++创建程序文件中文件的进程
- 在应用程序文件夹中安装 C/C++ 库"IGRAPH"
- 使用 Dev-C++ 5.2.0.2 进行调试 - 调试时找不到程序文件 gdb.exe
- 创建无需任何外部执行即可连续侦听的守护程序文件
- Qt单一应用程序文件已打开
- 问题.所有功能都可以在发布文件夹中工作,但不能在程序文件中工作
- 应用程序文件没有在不同的mac上运行