【发布时间】:2020-06-17 22:23:24
【问题描述】:
我正在尝试阅读动物列表,这很好用。然后我想将每个字符串拆分为name 和cmc 的两个子字符串,这也可以正常工作。但是我的cout 不起作用。
比如我的animal.txt是:
for 循环的输出应如下所示:
但实际输出是:
牛 牛 牛这是我的Animal.cpp:
#include <string>;
#include <vector>;
#include <fstream>;
#include "Animal.h"
using namespace std;
string cmc;
string name;
void Animal();
void Animal(string nameA) {
name = nameA;
}
void Animal(string nameA, string cmcValue) {
name = nameCard;
cmc = cmcValue;
}
void Animal::setName(string names)
{
name = names;
}
void Animal::setCmc(string cmcvalue) {
cmc = cmcvalue;
}
std::string Animal::getName() {
return name;
}
std::string Animal::getCmc() {
return cmc;
}
void Animal::openfileAnimal() {
ifstream inFileAnimal;
inFileAnimal.open("Animals.txt");
if (inFileAnimal.fail()) {
cerr << "error open this file" << endl;
exit(1);
}
string itemsAnimal;
std::vector<Animal> AllAnimals;
while (getline(inFileAnimal, itemsAnimal)) {
Animal c;
string t1 = itemAnimal;
size_t pos = t1.find("|");
//name (setname(sub))
string sub = t1.substr(0, pos);
c.setName(sub);
string t2 = t1.substr(sub1.length() + 1, t1.length());
string sub2 = t2.substr(0, t2.length());
c.setCmc(sub2);
AllAnimals.push_back(c);
}
for (int i = 0; i < 2; i++) {
std::cout <<AllAnimals.at(i).getName() << endl;
}
}
我阅读了其他类似我的 StackOverflow 问题,但对于我的示例,所有解决方案都不起作用。那么我的问题在哪里?我想这就像我一遍又一遍地修改同一个内存。
【问题讨论】:
-
为什么你的循环中有两次搜索
|?每行只包含一个|字符。 -
可能需要
Animal的实现。 -
...那些方法不是构造函数,那些对象也不是类的成员......