c++ - 从文件读取时如何从行中单独读取每个数字

标签 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
 */

例如,我想将 36 用于类似

的函数
create_list(int x, int y){}

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

最佳答案

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

从问题中不清楚您要做什么。如评论中所述,您可以使用 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";
  }
}

关于c++ - 从文件读取时如何从行中单独读取每个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55737618/

相关文章:

c++ - 错误 : unable to find string literal operator "" SLASHES

c++ - Ubuntu - 没有这样的文件或目录#include <string>

C++ while 循环读取输入

list - OCaml——如何检查两个列表是否匹配

linux - 在awk中将不同的行累积到不同的文件中

Java,从文件中读取抛出io异常 - 读取错误

c++ - OpenCV C++ 断言

php - 在 yii 中使用 listdata 连接 2 列

python - 列表列表更改意外地反射(reflect)在子列表中

python - Django 2.2 img 未加载