Closed. This question is off-topic。它当前不接受答案。
想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
5年前关闭。
我有一个用std :: ifstream打开的文件。我有一行要解析的代码:
并说我对width =“之后的” 384“感兴趣
我不知道如何最好地从该行中提取“ 384”,因为数字384根本不是恒定的。
谁能给我一个提示或指向涵盖此内容的优秀教程的链接?
既然您只对
现在我们需要找到
一旦我们检查它是否找到这个位置:
我们需要将其放入
由于我们实际上并不关心
现在我们使用提取器提取整数:
我希望这有帮助。这是该程序的完整示例:
想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
5年前关闭。
我有一个用std :: ifstream打开的文件。我有一行要解析的代码:
<image source="tileset/grass-tiles-2-small.png" width="384" height="192"/>
并说我对width =“之后的” 384“感兴趣
我不知道如何最好地从该行中提取“ 384”,因为数字384根本不是恒定的。
void parseFile(const std::string &mfName)
{
std::ifstream file(mfName);
std::string line;
if (file.is_open())
{
while (getline(file, line))
{
std::size_t found = line.find("width");
if (found != std::string::npos)
{
std::cout << found << std::endl;
}
}
}
else
std::cerr << "file failed to open" << std::endl;
}
谁能给我一个提示或指向涵盖此内容的优秀教程的链接?
最佳答案
这是您的文件:
<image source="tileset/grass-tiles-2-small.png" width="384" height="192"/>
既然您只对
width
感兴趣,我们应该首先获得整行:if (std::getline(file, line))
{
现在我们需要找到
width
。我们使用find()
方法做到这一点: std::size_t pos = line.find("width");
find()
中的字符串是我们要查找的值。一旦我们检查它是否找到这个位置:
if (pos != std::string::npos)
{
我们需要将其放入
std::stringstream
并解析出数据: std::istringstream iss(line.substr(pos));
substr()
调用用于选择字符串的子序列。 pos
是我们找到"width"
的位置。到目前为止,这是stringstream内部的内容: width="384" height="192"/>
由于我们实际上并不关心
"width"
,而是关心引号内的数字,因此我们必须在引号之前将所有内容都设为ignore()
。这样完成: iss.ignore(std::numeric_limits<std::streamsize>::max(), '"');
现在我们使用提取器提取整数:
int width;
if (iss >> width)
{
std::cout << "The width is " << width << std::endl;
}
我希望这有帮助。这是该程序的完整示例:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
void parseFile(const std::string& mfName)
{
std::ifstream file(mfName);
std::string line;
if (std::getline(file, line))
{
auto pos = line.find("width");
if (pos != std::string::npos)
{
std::istringstream iss(line.substr(pos));
int width;
if (iss.ignore(std::numeric_limits<std::streamsize>::max(), '"') &&
iss >> width)
{
std::cout << "The width is " << width << std::endl;
}
}
}
}