使用 fstream 和 cstring 写入文件
Writing to a file with fstream and cstring
#include <fstream>
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char filename[20] = "filename";
char userInput;
ofstream myFile;
cout << "Enter filename: ";
cin.getline(filename, sizeof(filename));
myFile.open(filename);
if(myFile.fail())
{
cout << "Error opening file: "
<< filename << "n";
return 1;
}
cout << "Add text to the file: ";
cin.get(userInput);
while(cin.good() && userInput)
{
myFile.put(userInput);
cin.get(userInput);
}
myFile.close();
return 0;
}
我在终止输入而不强制退出输入时遇到问题(它仍然写入文件(。
这是我应该做的
从用户接收一行输入,然后输出行到给定文件。这将持续到线路输入由用户是"-1",表示输入结束。
但是我无法计算出 -1 部分。任何帮助将不胜感激,其他一切似乎都有效。
你让事情变得比它们需要的要复杂一些。例如,为什么是C字符串而不是std::string
?使用正确的(标准提供的(类通常会导致更短、更简单和更易于理解的代码。首先尝试这样的事情:
int main()
{
std::string filename;
std::cout << "Enter filename" << std::endl;
std::cin >> filename;
std::ofstream file{filename};
std::string line;
while (std::cin >> line) {
if (line == "-1") {
break;
}
file << line;
}
}
首先,赋值要求从用户那里读取一行,get()
的字符输入不应该是要使用的函数。使用成员函数getline()
,就像接收文件名一样,并使用比较函数检查-1
:
for (char line[20]; std::cin.getline(line, sizeof line) && std::cin.gcount(); )
{
if (strncmp(line, "-1", std::cin.gcount()) == 0)
break;
myFile.write(line, std::cin.gcount());
}
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- 如何将Unicode CString(日语)打印到文本文件中
- 使用 fstream 和 cstring 写入文件
- G++ 4.6 问题没有标头 cstring 所需的 <bits/c++config.h> 文件
- 包括标准头文件.string.h还是cstring?或两者兼有
- 将CString写入.bin文件