需要帮助输入信息从文本文件到结构使用递归

Need help inputting info from text file to structure using recursion?

本文关键字:结构 递归 文件 文本 帮助 输入 信息      更新时间:2023-10-16

我是一个c++和编程的新手,所以请原谅我,我试图解释我自己。

我需要从.txt文件中输入信息到结构中。文本文件中的信息如下:

11 12 13

萨利

10 11 12

结构体几乎需要包含名称,a(在大小写1,11中),b(在大小写1,12中)和c(在大小写1,13中)。我希望递归地做这个,这样它就可以遍历每个名字和a, b和c。我真的不知道从哪里开始,我真的只是在寻找一些指导。

我在想也许把名字放进一个2D字符数组和a, b和c放进另一个3D字符数组?但我真的不确定如何做到这一点,或者这将有什么目的。

感谢所有的帮助!

好的,这是我得到的。虽然还处于早期阶段,但还是有意义的。

#include<iostream>
#include<fstream>
using namespace std;
const int max_names=100, a=100, b=100, c=100;
char names[max_names];
int num1[a];
int num2[b];
int num3[c];

int main()
{
    ifstream inFile;
    inFile.open("data.txt");
    while(!inFile.eof())
    {
        for(int i=0; i<max_names; i++)
        {
                inFile>>names[i]>>num1[i]>>num2[i]>>num3[i];
        }
    }
    return 0;
}
struct Person
{
    char names[max_names];
    int num1[a];
    int num2[b];
    int num3[c];
}

编辑:虽然我不想使用递归/结构,我必须为类。此外,在进一步研究我应该做什么之后,我需要创建一个结构体数组。这很难做到吗?我现在正在写我认为是一些代码,但我可能会完全离开。

我需要使用结构标识符。比如"struct Person"

编辑2:是的,递归,是的结构,没有迭代,没有类。它必须使用递归和结构

我会考虑在基本循环中使用ifstream从文件中读取。我认为递归不是这项工作的正确工具。

#include <iostream>
#include <fstream>
using namespace std;
int main () {    
  ifstream ifs("test.txt");
  while (ifs.good()) {
    struct foo;
    ifs >> foo.name >> foo.a >> foo.b >> foo.c;
  }
  ifs.close();    
  return 0;
}

这将允许任何空格分隔name, a, bc。如果您希望更小心地处理空白(例如允许在名称中使用空格),您可以使用peek()检查新行,或者切换到fscanf

看起来你想要定义一个class Person:

class Person {
  std::string name_;
  int numbers[3]; // Is this always 3 ? 
public:
  Person(std::istream& input)
  {
    std::getline(input, name_); // First line is name.
    input >> numbers[0] >> numbers[1] >> numbers[2];
    std::ignore(INT_MAX, 'n'); // Eat newline.
    // Can you 100% rely on the input being correct? 
    // If not, you'll need to throw an exception: if (input.fail()) throw ...
  }
  std::string const& name() const { return name_; }
  int a() const { return numbers[0]; }
  int b() const { return numbers[1]; }
  int c() const { return numbers[2]; }
};

使用这个类,您可以从IOstream构造person,直到遇到EOF。