如何只读取文本文件的第一行
How to read in only the first line of a text file?
我要打开的文本文件的名称是"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::string
和std::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.
}
相关文章:
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何使代码打印文本文件中的第一行?
- 如何在C++中以这种方式返回一行文本?
- 如何格式化我的文本文件以使其不会一遍又一遍地重复同一行?
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 需要从存档中读取一行文本.txt直到找到"hhh",然后转到下一行
- 如何在c ++中以一行(水平)打印两个文件的数据?如给定的.这两种形式来自两个不同的文本文件
- 到达分隔符时跳到文本文件的下一行
- 从文本文件中读取一行并将其存储在 C++ 中的 2D 矢量中
- 从文本文件中随机选取一行
- 从文本文件中的每一行读取数字,并计算数字重复的次数
- 为什么这一行不输出我的文本文件?
- 代码无尽写入文本文件的第一行
- 从二进制文件中抓取文本时,为什么 xdg_vtnr=8 是我的结果
- 为什么 c++ 编译器在中间放置空格时不输出下一行的文本?
- 从Windows应用程序的文本框中抓取文本
- 我怎么能读字符串和整数,在同一行从文本文件
- 如何在c++中从最后一行读取文本文件
- 说明:如何使用同一行打印文本后删除前一行-
- 每次一行显示文本文件,等待用户输入