从文件读取时如何从行中逐个读取每个数字

时间:2019-04-18 00:27:11

标签: c++ list file

需要有关如何从文件中读取数字以及如何从行中设置每个数字以设置功能的指南

我已经阅读了文件并能够将数字打印到屏幕上,但是我对如何打印这些数字以用于特定功能的功能已经有了一定的了解想要使用。例如我有

string line;
while(getline(file,line)){
    cout<<line<<"\n";
}
/* What the file is and what it prints out onto the screen
  3 6
  2 3 2
  2 1 6
  2 1 4
  1 2 3
  1 1 2
  2 1 8
 */

例如,我想将 3 6 用于

之类的功能
create_list(int x, int y){}

换句话说,每行中的每组数字将代表某些功能的输入

1 个答案:

答案 0 :(得分:0)

从输入行解析可变数量的整数

从问题中不清楚您正在尝试做什么。如注释中所述,您可以使用ifstream解析文件目录。我很懒,总是使用getline(<ifstream>, str)解析文件,然后使用istringstream解析行。这样我犯的错误更少。

问题之一是为什么您有多个行长。没关系,我根据每个输入行是1、2还是3个整数组成了要调用的函数。

关于使用流解析输入的伟大之处在于,流处理器可以解析int,double或其他内容。

如果您有任何疑问,请告诉我。

#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <vector>

int square(std::vector<int> &ints)
{
  return ints[0] * ints[0];
}

int rectangle(std::vector<int> &ints)
{
  return ints[0] * ints[1];
}

int volume(std::vector<int> &ints)
{
  return ints[0] * ints[1] * ints[2];
}

int main()
{

  std::ifstream file;
  file.open("example.txt");

  std::string str;
  while (getline(file, str)) {
    int parsed_int;
    std::vector<int> ints;
    int index = 0;

    std::stringstream stream(str);
    while (stream >> parsed_int) {
      ints.push_back(parsed_int);
      ++index;
    }

    int answer = 0;
    // index is the number of integers read on this line from the file
    switch (index) { 
      case 0:break;
      case 1:answer = square(ints);
        break;
      case 2:answer = rectangle(ints);
        break;
      case 3:answer = volume(ints);
        break;
      default:break;
    }
    std::cout << "Answer is " << answer << "\n";
  }
}
相关问题