英文:
Reading from a file is not returning the correct number of objects
问题
以下是您提供的代码部分的中文翻译:
if (event.command.get_command_name() == "change")
{
int count = 0;
vector<string> entities;
vector<int> health;
string myText;
string nameChoice = get<string>(event.get_parameter("user"));
ifstream MyReadFile("entities.txt");
while (getline(MyReadFile, myText, ':'))
{
if (count == 0)
{
entities.push_back(myText);
count += 1;
}
else if (count == 1)
{
if (entities.back() == nameChoice)
{
int temp = stoi(myText);
temp += get<int64_t>(event.get_parameter("numeral"));
cout << "temp" << temp;
health.push_back(temp);
count = 0;
}
else
{
health.push_back(stoi(myText));
count = 0;
}
}
}
MyReadFile.close();
ofstream MyFile("entities.txt", ios_base::out);
for (int i = 0; i < entities.size(); i++)
{
MyFile << entities[i] << ":";
MyFile << health[i] << "\n";
}
MyFile.close();
}
请注意,这是代码的中文翻译部分。如果您需要进一步的帮助或有其他问题,请随时提出。
英文:
I am coding a Discord bot, using the D++ library, that tracks the amount of health an entity has, and allows users on the server to modify the health of said entities.
My problem is with my command that handles when a user wants to modify the health value. The contents of the .txt
file are as follows:
Zombie:120
Skeleton:200
Vampire:500
If the user enters the command to modify the Vampire's health by -100, the file will instead look like this instead of lowering the vampire's health from 500 to 400:
Zombie:120
200
Vampire:500
Here is the relevant code:
if (event.command.get_command_name() == "change")
{
int count = 0;
vector<string> entities;
vector<int> health;
string myText;
string nameChoice = get<string>(event.get_parameter("user"));
ifstream MyReadFile("entities.txt");
while(getline(MyReadFile, myText, ':'))
{
if (count == 0)
{
entities.push_back(myText);
count += 1;
}
else if (count == 1)
{
if (entities.back() == nameChoice)
{
int temp = stoi(myText);
temp += get<int64_t>(event.get_parameter("numeral"));
cout << "temp" << temp;
health.push_back(temp);
count = 0;
}
else
{
health.push_back(stoi(myText));
count = 0;
}
}
}
MyReadFile.close();
ofstream MyFile("entities.txt", ios_base::out);
for (int i = 0; i < entities.size(); i++)
{
MyFile << entities[i] << ":";
MyFile << health[i] << "\n";
}
MyFile.close();
}
Through some debugging, I have found out that the while
loop is only looping 4 times, when it seemingly should be doing so 6 times.
As I am still a beginner at C++, I have been struggling to understand why, so I'd appreciate any guidance you could offer.
答案1
得分: 4
Sure, here is the translated content:
while(getline(MyReadFile, myText, ':'))
What's happening here is a demonstration of the Golden Rule Of Computer Programming, which says:
"Your computer always does exactly what you tell it to do instead of what you want it to do."
Here, you told your computer: "read from myReadFile
until the next :
character". So this is what your computer does here.
If the contents of the file are:
zombie:100
skeleton:200
mummy:300
Then:
-
The first time in this
while
loop, your computer reads "zombie" and puts that into yourmyText
(everything up until the first:
). -
The second time in this
while
loop, it reads "100\nskeleton" and puts that into yourmyText
(everything up until the second:
). -
The third time in this
while
loop, it reads "200\nmummy" and puts that into yourmyText
(everything up until the third:
). -
The fourth time in this
while
loop, it reads "300" and puts that into yourmyText
(everything up until the end-of-file).
This is what you told your computer to do: read until the next :
character, every time, so that's what your computer does.
It's pretty clear that this is not what you wanted your computer to do, but that's what you told it to do, so that's what it does.
I have been struggling to understand why
That's why, for the reasons explained above. std::getline()
reads input until a specific character gets read. End of story. No exceptions. By default it's the \n
character, but an optional third parameter specifies a different character. If it is specified it completely replaces the default \n
character, it does not supplement it.
英文:
> c++
> while(getline(MyReadFile, myText, ':'))
>
What's happening here is a demonstration of the Golden Rule Of Computer Programming, which says:
"Your computer always does exactly what you tell it to do instead of what you want it to do."
Here, you told your computer: "read from myReadFile
until the next :
character". So this is what your computer does here.
If the contents of the file are:
zombie:100
skeleton:200
mummy:300
Then:
-
The first time in this
while
loop, your computer reads"zombie"
and puts that into yourmyText
(everything up until the first:
). -
The second time in this
while
loop, it reads"100\nskeleton"
and puts that into yourmyText
(everything up until the second:
). -
The third time in this
while
loop, it reads"200\nmummy"
and puts that into yourmyText
(everything up until the third:
). -
The fourth time in this
while
loop, it reads"300"
and puts that into yourmyText
(everything up until the end-of-file).
This is what you told your computer to do: read until the next :
character, every time, so that's what your computer does.
It's pretty clear that this is not what you wanted your computer to do, but that's what you told it to do, so that's what it does.
> I have been struggling to understand why
That's why, for the reasons explained above. std::getline()
reads input until a specific character gets read. End of story. No exceptions. By default it's the \n
character, but an optional third parameter specifies a different character. If it is specified it completely replaces the default \n
character, it does not supplement it.
答案2
得分: 2
以下是翻译好的代码部分:
如果你感到有必要使用并行数组来保存相关的值,你应该使用一个保存`struct`/`class`类型的单一数组。
尽管如此,你没有正确使用`std::getline()`。你告诉它只读取到下一个`:`字符,而没有考虑换行符。你期望它在遇到*要么*`':'` *要么* `'\n'`时停止读取,但实际上它并不是这样工作的。
在处理*以行为基础的数据*时,你应该首先读取整行,然后根据需要解析该行。
可以尝试像这样改进代码:
if (event.command.get_command_name() == "change")
{
struct entity
{
string name;
int health;
};
vector<entity> entities;
string line, nameChoice = get<string>(event.get_parameter("user"));
ifstream MyReadFile("entities.txt");
while (getline(MyReadFile, line))
{
istringstream iss(line);
entity e;
getline(iss, e.name, ':');
iss >> e.health;
if (e.name == nameChoice)
{
e.health += get<int64_t>(event.get_parameter("numeral"));
cout << "temp" << e.health;
}
entities.push_back(e);
}
MyReadFile.close();
ofstream MyFile("entities.txt");
for (size_t i = 0; i < entities.size(); ++i)
{
MyFile << entities[i].name << ':' << entities[i].health << '\n';
}
MyFile.close();
}
或者,如果你在读取每个健康值后直接使用std::istringstream
可能会更简单,例如:
if (event.command.get_command_name() == "change")
{
struct entity
{
string name;
int health;
};
vector<entity> entities;
string nameChoice = get<string>(event.get_parameter("user"));
entity e;
ifstream MyReadFile("entities.txt");
while (getline(MyReadFile, e.name, ':'))
{
MyReadFile >> e.health;
MyReadFile.ignore(numeric_limits<streamsize>::max(), '\n');
if (e.name == nameChoice)
{
e.health += get<int64_t>(event.get_parameter("numeral"));
cout << "temp" << e.health;
}
entities.push_back(e);
}
MyReadFile.close();
ofstream MyFile("entities.txt");
for (size_t i = 0; i < entities.size(); ++i)
{
MyFile << entities[i].name << ':' << entities[i].health << '\n';
}
MyFile.close();
}
或者,如果你在读取原始文件的同时写入一个单独的文件,可以完全摒弃std::vector
,例如:
if (event.command.get_command_name() == "change")
{
string nameChoice = get<string>(event.get_parameter("user"));
string entity;
int health;
ifstream MyReadFile("entities.txt");
ofstream MyFile("new_entities.txt");
while (getline(MyReadFile, entity, ':'))
{
MyReadFile >> health;
MyReadFile.ignore(numeric_limits<streamsize>::max(), '\n');
if (entity == nameChoice)
{
health += get<int64_t>(event.get_parameter("numeral"));
cout << "temp" << health;
}
MyFile << entity << ':' << health << '\n';
}
MyReadFile.close();
MyFile.close();
remove("entities.txt");
rename("new_entities.txt", "entities.txt");
}
英文:
Any time you feel the need to use parallel arrays to hold related values, you should instead use a single array that holds a struct
/class
type.
That said, you are not using std::getline()
correctly. You are telling it to read only until the next :
character, without any regards to line breaks. You are expecting it to stop reading when it encounters either ':'
or '\n'
, but that is simply not how it works.
When dealing with line-oriented data, you should read a whole line first, and then parse the line as needed.
Try something more like this:
if (event.command.get_command_name() == "change")
{
struct entity
{
string name;
int health;
};
vector<entity> entities;
string line, nameChoice = get<string>(event.get_parameter("user"));
ifstream MyReadFile("entities.txt");
while (getline(MyReadFile, line))
{
istringstream iss(line);
entity e;
getline(iss, e.name, ':');
iss >> e.health;
if (e.name == nameChoice)
{
e.health += get<int64_t>(event.get_parameter("numeral"));
cout << "temp" << e.health;
}
entities.push_back(e);
}
MyReadFile.close();
ofstream MyFile("entities.txt");
for (size_t i = 0; i < entities.size(); ++i)
{
MyFile << entities[i].name << ':' << entities[i].health << '\n';
}
MyFile.close();
}
Alternatively, you can omit the std::istringstream
if you instead simply ignore()
the next line break after reading each health value, eg:
if (event.command.get_command_name() == "change")
{
struct entity
{
string name;
int health;
};
vector<entity> entities;
string nameChoice = get<string>(event.get_parameter("user"));
entity e;
ifstream MyReadFile("entities.txt");
while (getline(MyReadFile, e.name, ':'))
{
MyReadFile >> e.health;
MyReadFile.ignore(numeric_limits<streamsize>::max(), '\n');
if (e.name == nameChoice)
{
e.health += get<int64_t>(event.get_parameter("numeral"));
cout << "temp" << e.health;
}
entities.push_back(e);
}
MyReadFile.close();
ofstream MyFile("entities.txt");
for (size_t i = 0; i < entities.size(); ++i)
{
MyFile << entities[i].name << ':' << entities[i].health << '\n';
}
MyFile.close();
}
Alternatively, you can get rid of the std::vector
altogether if you write to a separate file while reading the original file, eg:
if (event.command.get_command_name() == "change")
{
string nameChoice = get<string>(event.get_parameter("user"));
string entity;
int health;
ifstream MyReadFile("entities.txt");
ofstream MyFile("new_entities.txt");
while (getline(MyReadFile, entity, ':'))
{
MyReadFile >> health;
MyReadFile.ignore(numeric_limits<streamsize>::max(), '\n');
if (entity == nameChoice)
{
health += get<int64_t>(event.get_parameter("numeral"));
cout << "temp" << health;
}
MyFile << entity << ':' << health << '\n';
}
MyReadFile.close();
MyFile.close();
remove("entities.txt");
rename("new_entities.txt", "entities.txt");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论