从 C++ 中的文件中获取特定位置的详细信息

grab the detail from particular location from file in c++

本文关键字:定位 位置 详细信息 文件 C++ 获取      更新时间:2023-10-16
char a[133];
char x[4]="ccc";
    int line=3,count=1;
    //string aa;
    //cin>>aa;
    ifstream out("text");

    while(out.getline(a,4,':')&&(strncmp(a,x,4)))
            {cout<<"hi";
                    cout<<a<<endl;
            out.getline(a,4,'n');
}
out.close();
return 0;`

在文本文件中

aaa:1111111
bbb:222222
ccc:333333
ddd:444444

我想跳到特定的行上并抓住细节。 但我没有得到它。 请指导我如何在C ++中做到这一点

毕竟得到了解决方案。您也可以看到结果

在这里

int main(){
    ifstream in ("text");
    if(!in){cout<<"cannot open"<<endl;}
    string buffer;
    int line_count=1; size_t line=1;
    while(line){
      getline(in,buffer);
      if(!buffer.find_first_of("bbb:"))
      {
         cout<<line<<endl;
         break;
      }
      else
      {
       line=line+1;
      }
    }
    cout<<buffer<<endl;
    for(int line_count=0;line_count<line-1&&getline(in,buffer);line_count++)
    {
    }
    getline(in,buffer);
    in.close();
    return 0;
 }

再次感谢

首先,您可以将每一行读入如下std::string

std::ifstream in("text");
std::string buffer;
int line_count = 0;
// discard lines until we arrive at the desired line or an error/eof occurs
for(int line_count = 0; 
    line_cout < line && std::getline(in, buffer);
    line_count++) {}
if(in) { // check if last extraction was successful
    // process line stored in buffer
}
else {
    if(in.eof())
        std::cout << "Line-number was invalid" << std::endl;
    else
        std::cout << "An error occurred" << std::endl;
    return -1;
}

您可以在此处找到有关使用iostreams读取文件的一些详细信息。然后,您可以处理该行。使用成员函数std::string::find_first_of您可以找到':',并使用成员函数std::string::substr您可以在该位置拆分字符串。

请注意,此方法仅适用于问题中所述的简单格式。对于像"ab:c":"content"这样的格式,它不会像您期望的那样工作。如果你有这样的格式,你需要编写一个更复杂的解析器,最好使用 Boost.Spirit.Qi .