我有一个小程序,用于从文件中复制一个小短语,但似乎我对seekg()的工作方式有误解,或者我的代码中存在问题,导致该函数无法按预期工作。
文本文件包含:
//介绍
以前注意=假
该代码旨在将单词“false”复制到字符串中
std::fstream stats("text.txt", std::ios::out | std::ios::in);
//String that will hold the contents of the file
std::string statsStr = "";
//Integer to hold the index of the phrase we want to extract
int index = 0;
//COPY CONTENTS OF FILE TO STRING
while (!stats.eof())
{
static std::string tempString;
stats >> tempString;
statsStr += tempString + " ";
}
//FIND AND COPY PHRASE
index = statsStr.find("previouslyNoted="); //index is equal to 8
//Place the get pointer where "false" is expected to be
stats.seekg(index + strlen("previouslyNoted=")); //get pointer is placed at 24th index
//Copy phrase
stats >> previouslyNotedStr;
//Output phrase
std::cout << previouslyNotedStr << std::endl;
但无论出于何种原因,程序输出:
=假
我期望发生的事情:
我相信我将 get 指针放在文件的第 24 个索引处,这是短语“false”开始的地方。然后程序将从该索引开始输入,直到遇到空格字符,或者遇到文件末尾。
实际发生了什么:
无论出于何种原因,get 指针在预期之前启动了一个索引。我不确定为什么。非常感谢您解释出了什么问题/我做错了什么。
另外,我确实知道我可以简单地从我希望的位置开始将previousNotedStr设为 statsStr的子字符串,并且我已经成功地尝试过。我真的只是在这里做实验。