【问题标题】:Is it possible to store newline characters read from a text file in c++?是否可以在 C++ 中存储从文本文件中读取的换行符?
【发布时间】:2016-04-02 17:23:22
【问题描述】:

文本文件如下所示:

this is a test \n to see if it breaks into a new line.

c++ 看起来像这样:

string test;
ifstream input;
input.open("input.txt");
getline(input, test);

如果您将“测试”写入输出文件,它看起来像这样:

this is a test \n to see if it breaks into a new line.

我希望它在写入文件时遇到“\n”字符时换行。

【问题讨论】:

  • \n 仅在源代码的字符串文字中写入时才具有“换行符”的含义。在文本文件中(或基本上在其他任何地方),它本身就是一个反斜杠,后跟一个 n。在输入文件中获取换行符的最简单方法是按 Enter ;)
  • 是的,我尝试将它作为一个变量存储在一行中,然后可以将其写成两行。
  • @Jay 两个答案等着你。我会说,你应该阅读并接受一份。

标签: c++ file io


【解决方案1】:

这样做:

#include <fstream>
using namespace std;

int main() {
  fstream file;
  file.open("test.txt");
  string test = "this is a test \n to see if it breaks into a new line.";
  file << test;
  file.close();
  return 0;
}

“text.txt”的结果:

this is a test
 to see if it breaks into a new line..

灵感来自:adding a newline to file in C++

【讨论】:

    【解决方案2】:

    为了好玩,为了最终的效率,我们可以消除对std::string的需要,并通过在编译时进行计算字符串长度的需要:

    #include <fstream>
    #include <utility>
    #include <algorithm>
    
    using namespace std;
    
    template<std::size_t N>
    struct immutable_string_type
    {
        typedef const char array_type [N+1];
    
        static constexpr std::size_t length() { return N; }
        constexpr immutable_string_type(const char (&dat) [N + 1])
        : _data { 0 }
        {
            auto to = _data;
            auto begin = std::begin(dat);
            auto end = std::end(dat);
            for ( ; begin != end ; )
                *to++ = *begin++;
        }
    
        constexpr array_type& data() const {
            return _data;
        }
    
        char _data[N+1];
    };
    
    template<std::size_t N>
    constexpr immutable_string_type<N-1> immutable_string(const char (&dat) [N])
    {
        return immutable_string_type<N-1>(dat);
    }
    
    int main() {
        ofstream file;
        file.open("test.txt");
        constexpr auto test = immutable_string("this is a test \n to see if it breaks into a new line.");
        file.write(test.data(), test.length());
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      相关资源
      最近更新 更多