2016-04-13 11 views
-4

オープンしたいテキストファイルの名前は "map.txt"です。私は、ファイルの最初の行をコンソールに読み込みたいだけです。テキストファイルの最初の行は次のとおりです。ここでテキストファイルの最初の行だけを読み込むには?

E1 346 473 1085 3725 30 30

は、私がこれまで持っているコードです。 WhozCraig同様

ifstream file; 

file.open("map.txt"); 

if (!file) //checks to see if file opens properly 
{ 
    cerr << "Error: Could not find the requested file."; 
} 
    /******* loop or statement needed to read only first line here?**********/ 
+0

おそらく 'while()' – drescherjm

+3

'std :: string行の代わりに' getline() 'が必要かもしれません。 std :: getline(file、line) '、私はあなたが最初の行を読むときに完了しているので、私は"ファイルを読み終えたら停止する "という意味がないことを認めます。 – WhozCraig

+0

@WhozCraigはい。ファイル全体をコンソールに読み込ませた別のプログラムからその部分をコピーしました。私はあなたがそれを言及した今、それを削除します。 – littmuslozenge

答えて

1

std::stringstd::getline()を使用し、彼らのコメントで述べています。

ifstream file; 

file.open("map.txt"); 
string line; 

if (!file) //checks to see if file opens properly 
{ 
    cerr << "Error: Could not find the requested file."; 
} 
else 
{ 
    if (getline(file, line)) cout << line; // Get and print the line. 
    file.close(); // Remember to close the file. 
}