循环将文本文件的每一行处理到三个数组之一
我正在尝试创建一个循环,将文本文件的行分割成不同的向量,其中“persons”包含所有行,“v1”包含姓名,“v2”包含年龄和年龄。 “v3”包含宠物。我已经能够将所有行推到“人”,但是我如何迭代人,以便人[0]=姓名,人[1]=年龄,人[2]=宠物,人[4]=姓名等。 ...?我编写的代码陷入了无限循环。
#include <io>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
ifstream people("myfile.txt");
vector<string> persons;
vector<string> first_names;
vector<float> ages;
vector<string> pets;
string l;
float age;
if(!people)
{
printf("fail");
system("pause");
return -1;
}
else
{
while(getline(people, l))
{
if (l.size() > 0)
{
people.push_back(l)
}
}
int num = people.size();
for (int i = 0; i < num; i + 3)
{
first_names.push_back(people[i]); // These are the
ages.push_back(stof(people[i+1])); // lines created to
pets.push_back(people[i+2]); // push to seperate
} // arrays.
return 0
}
}
文本文件示例
Bob
25.5
Snake
Kerry
29.5
Dog
I am trying to create a loop to split lines of a text file into different vectors where "persons" contains all lines, "v1" contains names, "v2" contains ages & "v3" contains pets. I have been able to push all lines to "persons" but how would I iterate over persons so that persons[0] = name, persons[1] = age, persons[2] = pet, persons[4] = name etc....? The code I have written gets stuck in an infinite loop.
#include <io>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
ifstream people("myfile.txt");
vector<string> persons;
vector<string> first_names;
vector<float> ages;
vector<string> pets;
string l;
float age;
if(!people)
{
printf("fail");
system("pause");
return -1;
}
else
{
while(getline(people, l))
{
if (l.size() > 0)
{
people.push_back(l)
}
}
int num = people.size();
for (int i = 0; i < num; i + 3)
{
first_names.push_back(people[i]); // These are the
ages.push_back(stof(people[i+1])); // lines created to
pets.push_back(people[i+2]); // push to seperate
} // arrays.
return 0
}
}
Text file example
Bob
25.5
Snake
Kerry
29.5
Dog
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是错误的:
应该如此
,否则
i
将始终为 0 并且永远不会超过num-1
。This is wrong:
It should be
otherwise
i
will always be 0 and never more thannum-1
.