簡體   English   中英

需要幫助將信息從文本文件輸入到使用遞歸的結構?

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

我是 C++ 和一般編程的新手,所以請耐心等待我嘗試解釋自己。

我需要將信息從 a.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];
}

編輯:雖然我不想使用遞歸/結構,但我必須使用 class。 此外,在進一步查看我應該做什么之后,我需要創建一個結構數組。 這很難做到嗎? 我現在正在處理我認為的一些代碼,但我可能會完全離開。

我需要使用結構標識符。 像“結構人”

編輯 2:是的,遞歸,是結構,沒有迭代,沒有 class。 它必須使用遞歸和結構。

我會考慮使用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;
}

這將允許任何空格分隔nameabc 如果您想更加小心空格(例如允許名稱中的空格,您可以使用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]; }
};

使用此 class,您可以從 IOstream 構造 Persons,直到遇到 EOF。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM