【问题标题】:How to get cursor to next line after using ">>" operator when reading from file从文件读取时使用“>>”运算符后如何将光标移至下一行
【发布时间】:2015-06-20 15:09:25
【问题描述】:

我正在尝试从如下所示的 .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");
}

【问题讨论】:

  • 添加c++标签,更快获得帮助

标签: c++ string ifstream getline stringstream


【解决方案1】:

我想你想念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");
}

运算符&gt;&gt; 读取分隔符之间的标记。默认情况下,空格和换行符是分隔符。因此,在第一个循环中最后一个运算符 &gt;&gt; 调用之后,您仍然在同一行,第一个 getline() 调用仅读取换行符。

【讨论】:

  • 工作就像一个魅力。谢谢。
猜你喜欢
  • 2019-06-14
  • 2011-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-21
相关资源
最近更新 更多