C++ 如何在C++;?

C++ 如何在C++;?,c++,file-io,C++,File Io,可能重复: 我有一个C++的文本文件,看起来像这样: [layer] type=background data= 1,1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,11,1,1,1,1,1,1,1,1,1

可能重复:

<>我有一个C++的文本文件,看起来像这样:

[layer]
type=background
data=
1,1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1,1,
但是,我在同一个文本文件中有多个层,每个层都必须以不同的方式构建,但是我需要为每个层获取“data=”中显示的值

我将如何实现这一点?我尝试过的一种方法是将它们存储到向量中,但在将所有内容存储到向量中之后,我没有想到从向量中提取这些值的解决方案

while(file >> line)
    {
        words.push_back(line);
    }

    if(find(words.begin(), words.end(), "[header]") != words.end())
    {
        for(int i = find(words.begin(), words.end(), "[header]"); words.at(i) != "\n"; i++)
        {
            word += words.at[i];
        }
    }
    cout << word << endl;
    file.close();
while(文件>>行)
{
字。推回(线);
}
如果(查找(words.begin()、words.end()、“[header]”)!=words.end())
{
for(int i=find(words.begin(),words.end(),“[header]”);words.at(i)!=“\n”;i++)
{
单词+=单词。在[i];
}
}

这相当容易。您知道数据从“data=”行之后开始,以“[layer]”行结束,因此只需搜索它们:

std::ifstream f("your_file");
std::string string;
while( f >> string && !f.eof() )
{
    if( string == "data=")//If we found the "data=" string, we know data begins next.
    {
        std::cout << std::endl << "new layer's data found" << std::endl;
        f >> string;//going to the next string (the actual data)
        //while we don't see the "[layer]" which indicates the end of data...
        while( string != "[layer]"  && !f.eof() )"[layer]"
        {
            std::cout << string;//...we output the data found
            f >> string;//and continue to the next string
        }
    }
}
std::ifstream f(“您的_文件”);
std::字符串;
while(f>>字符串&&!f.eof())
{
if(string==“data=”)//如果我们找到了“data=”字符串,我们知道数据下一步开始。
{

std::cout Cause引入一个成熟的XML解析器并执行DOM操作比读取ini文件中的几行更有意义…听起来很合法,我不明白为什么使用正确的文本数据格式是过分的。如果有的话,这是一个很好的实践。如果XML是正确的文本数据格式,我同意你的观点。对于这样的情况,ini文件,JSON、YAML等更有意义。@Charlie,因为要使用XML,你需要搞乱文档结构、节点、带一个完整的解析器等等。当你必须杀死一只苍蝇时,你不会建造高斯加农炮,是吗?@CharliePryn:一个主要原因:XML在结构上通常比在实际数据上占用更多的空间。任何需要对结构的投入不多,特别是对于这样简单的东西,在我看来,这很不适合这份工作。1:“这很容易。”-显然,出错的可能性很大。你应该检查
[.*]
,这样你就知道你在哪个部分,然后扫描数据=,需要将值提取到
int
s的向量中。
eof()的使用
检查错误-例如-
而(f>>string>>!f.eof())
可以成功读取字符串,但仍然达到eof(您可以在Linux/UNIX上使用
echo-n value | app
进行测试,但将无法处理该字符串。