2016-10-18 6 views
8

ファイルから情報を取得する際に文字列リテラルを含める方法に関する質問があります。私はより良い理解のために自分のコードをお見せしましょう:文字リテラルを含めるには?

Program.b

print \"Hello World\n\"; print \"Commo Estas :)\n\"; print \"Bonjour\";print \"Something\"; return 0; 

main.cppに(私はこの質問のために必要とされるものに実際のファイルを最小化している):

int main() 
{ 
    std::string file_contents; 
    std::fstream file; 
    file.open("Program.b"); 
    std::ifstream file_read; 
    file_read.open("Program.b"); 

    if(file_read.is_open()) 
     while(getline(file_read,file_contents)); 

    cout << file_contents << endl; 

} 

私はfile_contentsを印刷するときに、今、私が手:

print \"Hello World\n\"; print \"Commo Estas :)\n\"; print \"Bonjour\";print \"Something\"; return 0; 

\nが含まれていることがわかります。それを実際の文字リテラルにする方法はありますか?それで、実際に印刷すると新しい行が印刷されますか? (私は引用符のために同じことをしたいと思う)

+1

実行時にファイルを読む必要がありますか?それ以外の場合は、おそらくプリプロセッサを使用する可能性があります。 –

+0

いいえ、@πάνταῥεneedは必要ありません。私はプリプロセッサを使うことができますか? .. #define toStr(x)#x'? – amanuel2

+0

あなたが望むことをするリンクがあります:[リンク](http://stackoverflow.com/questions/5612182/convert-string-with-explicit-escape-sequence-into-relative-character) – Rikocar

答えて

6

このような何か試してみてください:

Program.b

R"inp(print "Hello World\n"; print "Commo Estas :)\n"; print "Bonjour";print "Something"; return 0;)inp" 

main.cppに

int main() { 
    std::string file contents = 
    #include "Program.b" 
    ; 
    std::cout << file_contents << std::endl; 

} 

また、それが少し読みやすくするためにProgram.bを変更することができます。

R"inp(
print "Hello World\n"; 
print "Commo Estas :)\n"; 
print "Bonjour"; 
print "Something"; 
return 0; 
)inp" 

ランタイム変異体は、単純に次のようになります。

print "Hello World\n"; 
print "Commo Estas :)\n"; 
print "Bonjour"; 
print "Something"; 
return 0; 

メイン

Program.b .cpp

int main() 
{ 
    std::string file_contents; 
    std::fstream file; 
    file.open("Program.b"); 
    std::ifstream file_read; 
    file_read.open("Program.b"); 

    if(file_read.is_open()) { 
     std::string line; 
     while(getline(file_read,line)) { 
      file_contents += line + `\n`; 
     } 
    } 

    cout << file_contents << endl; 

} 
+0

を印刷したときにうまくいくようです:) – Rakete1111

+0

@ Rakete1111もちろん、;) –

+0

なぜ 'R' ?.... – amanuel2

2

簡単な検索+置換ができます。

std::size_t pos = std::string::npos; 
while ((pos = file_contents.find("\\n")) != std::string::npos) 
    file_contents.replace(pos, 1, "\n"); 

//Every \n will have been replaced by actual newline character 
+0

ワウは良いアイデアのように思えるが、もっと必要なときにちょっと退屈になるだろう。 〜に? – amanuel2

+0

@ amanuel2特殊文字を実際の表現で削除する汎用関数をいつでも作ることができます。 – Rakete1111

+0

ありがとうございます。 [** this **](https://gist.github.com/amanuel2/b8d02b026715e54857313066c799316d)を参照してください。次の時代のチャウに行こう! – amanuel2

関連する問題