使用 fstream 和 cstring 写入文件

Writing to a file with fstream and cstring

本文关键字:文件 cstring fstream 使用      更新时间:2023-10-16
    #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());
}