如何只读取文本文件的第一行

How to read in only the first line of a text file?

本文关键字:一行 取文本 何只读 只读 文件      更新时间:2023-10-16

我要打开的文本文件的名称是"map.txt"。我只想在控制台中读取文件的第一行。文本文件的第一行是:

E1 346 473 1085 3725 30

这是我目前掌握的代码。

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?**********/

就像WhozCraig在评论中所说的那样,使用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.
}