从文件读取时如何使用运算符后将光标移动到下一行">>"

How to get cursor to next line after using ">>" operator when reading from file

本文关键字:gt 一行 移动 读取 文件 何使用 运算符 光标      更新时间:2023-10-16

我正在尝试从一个.txt文件中读取信息,如下所示。要读取前2行整数,我使用">>"运算符将它们读取到一个数组中。我的问题是,我想读取字符串的下一行(全部),这样我就可以将其转换为流并解析它,然而,当我尝试简单地使用getline时,它实际上并没有读取字符串中的任何内容,这让我认为光标实际上并没有移动到下一行,我想知道如何执行此操作或任何其他可以用于保存目的的方法。txt文件的结构如下:

2
10 10 10 10 10 10 20 20 20 15 15 15 15 15 15 15 20 30 20 15 15 10 10 10
765DEF 01:01:05:59 enter 17
ABC123 01:01:06:01 enter 17
765DEF 01:01:07:00 exit 95
ABC123 01:01:08:03 exit 95

我的代码如下所示:

#include<iostream>
#include<fstream>
#include<string>
#include <sstream>
using namespace std;

int main()
{
int arr[24];
int milemarker;
int numberofCases;

ifstream File;
File.open("input.txt");
File >> numberofCases;
for (int i = 0; i < 24; i++)
{
File >> arr[i];
}
for (int i = 0; i < 24; i++)
{ 
cout << arr[i] << " ";
}
cout << endl;
string line;
getline(File, line);
cout << line;

system("pause");
}

我想你错过了getline()呼叫:

#include<iostream>
#include<fstream>
#include<string>
#include <sstream>
using namespace std;

int main()
{
int arr[24];
int milemarker;
int numberofCases;

ifstream File;
File.open("input.txt");
File >> numberofCases;
for (int i = 0; i < 24; i++)
{
File >> arr[i];
}
for (int i = 0; i < 24; i++)
{ 
cout << arr[i] << " ";
}
cout << endl;
string line;
getline(File, line);
getline(File, line);
cout << line;

system("pause");
}

运算符>>读取分隔符之间的标记。默认情况下,空格和新行是分隔符。所以在第一个循环中的最后一个运算符>>调用之后,您仍然在同一行上,并且第一个getline()调用只读取新行字符。