为什么循环不会停止?C++

why whould this while loop won't stop? c++

本文关键字:C++ 循环 为什么      更新时间:2023-10-16

这是一个代码,用于读取.txt文件并通过:和打印结果来拆分它。但我被困在了while循环上。这是我的代码。

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
string* split(const string& str, const string& delim) {
string* string_list = new string[10];
int idx = 0;
char *token = strtok(const_cast<char*>(str.c_str()), delim.c_str());
while (token != NULL) {
string_list[idx] = token;
token = strtok(NULL, delim.c_str());
++idx;
}
return string_list;
}
struct Item {
string name;
string age;
string id;
string subject[10];
};
struct Item* create_item() {
struct Item* pitem = new Item;
return pitem;
};
void insert_item(struct Item *prev_item, struct Item *item) {
item = (prev_item + 5);
}

int main() {
string student, student2;
string *string_list, *subject, *string_list2, *subject2;
struct Item* pstudent, *pstudent2;
ifstream fin;
fin.open("input.txt");
fin >> student;
while (student != "n") {
string_list = split(student, ":");
pstudent = create_item();
pstudent->name = *string_list;
pstudent->age = *(string_list + 1);
pstudent->id = *(string_list + 2);
subject = split(*(string_list + 3), ",");
for (int i = 0; i < 10; i++) {
if (*(subject + i) != "") {
pstudent->subject[i] = *(subject + i);
}
}
cout << *(string_list+1) << endl;
fin >> student2;
string_list = split(student2, ":");
pstudent2 = create_item();
insert_item(pstudent, pstudent2);
pstudent2->name = *(string_list);
pstudent2->age = *(string_list + 1);
pstudent2->id = *(string_list + 2);
subject2 = split(*(string_list + 3), ",");
for (int i = 0; i < 10; i++) {
if (*(subject2 + i) != "") {
pstudent2->subject[i] = *(subject2 + i);
}
}
}
cout << pstudent2->name << endl;
fin.close();
return 0;
}

我仍在处理这段代码,但是main((中的while循环不会停止。我希望它在输入.txt文件输入是新行时停止。

输入.txt是

玛丽:20:287:数学,算法 汤姆:21:202:数学,英语 嘻嘻:20:256:数学

提前感谢!

不要尝试在循环正文中处理多个学生。

不要尝试编写链接列表类型,而是使用现有集合类型。

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using strings_view = std::vector<std::string_view>;
strings_view split(std::string_view str, char delim) {
strings_view view;
while (str.size()) 
{
auto pos = str.find(delim);
view.push_back(str.substr(0, pos - 1));
str = str.substr(pos + 1);
}
return view;
}
struct Item {
std::string name;
std::string age;
std::string id;
std::vector<std::string> subject;
};
int main() {
std::vector<Item> students;
std::ifstream fin("input.txt");
for (std::string line; get_line(fin, line);) {
strings_view view = split(line, ':');
Item student;
student.name = view[0];
student.age = view[1];
student.id = view[2];
string_view subject = split(view[3], ',')
student.subject.assign(subject.begin(), subject.end());
students.push_back(student);
}
std::cout << students[1].name << std::endl;
return 0;
}