2016-04-02 20 views
1

Metin dosyası şuna benzer:Bir metin dosyasından okunan yeni satır karakterlerini C++ içinde depolamak mümkün mü?

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

C++ şuna benzer:

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

I: Eğer bir çıkış dosyasına 'test' yazarsanız şöyle

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

Bir dosyaya yazılırken '\ n' karakteriyle karşılaştığında yeni bir satıra girmesini ister.

+1

'\ n yalnızca kaynak kodunuzda bir dize değişmezinin içine yazıldığında" yeni satır "anlamına gelir. Bir metin dosyasının içinde (ya da temelde başka bir yerde) sadece kendisidir: bir ters eğik çizgi ardından bir n. Giriş dosyasında yeni satır elde etmenin en kolay yolu, Enter tuşuna basmak olacaktır;) – Thomas

+0

Evet, hepsini tek bir satır olarak tek bir değişken olarak kaydetmeyi denedim, sonra bunu iki satır olarak yazabilecektim. – Jay

+0

@Jay iki cevap sizi bekliyor. Onları okumalı ve bir tanesini kabul etmelisin. – gsamaras

cevap

0

bunu böyle yapın: "text.txt" nin

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

Sonucu: esinlenerek

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

: adding a newline to file in C++

0

Sadece eğlence için, mükemmel verimlilik için, std::string gereksinimini kaldırabiliriz ve dizinin uzunluğunu doi ile hesaplamaya gerek kalmaz. derleme zamanı:

#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; 
} 
İlgili konular