2016-04-02 13 views
1

テキストファイルには、次のようになります。テキストファイルから読み込んだ改行文字をC++で保存することはできますか?

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

C++は次のようになります。

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

I:あなたは出力ファイルに 'test' と書いた場合、それはこのようになります

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

それがファイルに書き込まれるときに '\ n'文字に遭遇したときに改行するようにしてください。 "TEXT.TXT" の

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

結果:触発され

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

+1

'\ n'は、ソースコードの文字列リテラルの中に書かれたときにのみ、「改行」の意味を持ちます。テキストファイルの中(または基本的にはどこか他の場所)には、バックスラッシュの後ろにnが続くだけです。 ) – Thomas

+0

ええと、それを1行に1変数として保存して、2行として書くことができるようにtrynigしていたのですが、入力ファイルに改行を入れるのが最も簡単でした。 – Jay

+0

@Jayがあなたを待っています。あなたはそれらを読んで1つを受け入れるべきです、私は言うでしょう。 – gsamaras

答えて

0

、我々はstd::stringの必要性を取り除き、doiによって文字列の長さを計算する必要性を取り除くことができたコンパイル時に:

#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; 
} 
関連する問題