简体   繁体   中英

Is it possible to store newline characters read from a text file in c++?

Text file looks like this:

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

c++ looks like this:

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

if you write 'test' to an output file it looks like this:

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

I want it to break into a new line when it encounters the '\\n' character as it is written to a file.

Do it like this:

#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;
}

Result of "text.txt":

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

Inspired by: adding a newline to file in C++

Just for fun, for ultimate efficiency, we could remove the need for std::string and remove the need for computing the length of the string by doing it at compile time:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM