2012-02-23 54 views
0
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;` 

在文本文件中抓住从特定位置的细节,从文件中的C++

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; 
} 

再次感谢

回答

2

首先,你可以阅读每一行成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; 
} 

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

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

+0

非常感谢您的回复。但是,如果我们不知道行号,该怎么办?我们只知道我们需要'bbb'行的详细信息。再次感谢 – Newbie123 2012-02-23 10:22:24

+0

您可以使用'std :: string :: find_first_of(const std :: string&)'检查一行是否以给定的字符串开始 - 如果行以给定的字符串开头,它将返回'0'。因此,例如,'buffer.find_first_of(“bbb:”)'将在您的示例中为第二行返回“0”,并为所有其他行返回非零值。 – 2012-02-23 10:31:21

+0

谢谢你的队友!你是救世主.... – Newbie123 2012-02-23 13:02:20