需要帮助输入信息从文本文件到结构使用递归
Need help inputting info from text file to structure using recursion?
我是一个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
, b
和c
。如果您希望更小心地处理空白(例如允许在名称中使用空格),您可以使用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。
相关文章:
- 二叉树结构平衡,使用递归时EXC_BAD_ACCESS
- 如何在C++中表示JSON文档的递归对象结构?
- C++ 递归返回 nullptr 中的结构 ?.
- 递归如何使用堆栈数据结构
- 如何制作递归编译时间变异结构模板
- 没有指针的递归结构?(霍夫曼)
- 使用boost::序列化递归图结构时,如何防止堆栈溢出
- 递归结构的向量有内存问题
- C++,一个通用递归模板函数,用于遍历树状结构
- 如果结构作为递归函数中的参数传递,如何初始化结构的成员变量
- 节省增强精神递归匹配结果为C 结构
- 用载体建立在苍蝇递归结构上
- 双递归结构
- 如何计算递归结构
- 使用结构和递归查找整数数组中的最大数字
- 协议缓冲区、Apache Thrift或任何其他数据结构序列化协议中的递归数据结构
- 递归类型真的是构建不连续的任意大小数据结构的唯一方法吗
- 可变参数模板实例化中的无限递归,试图构建任意深度的树状结构
- 递归数据结构的前向声明
- 正在分析boost::spirit上的递归结构