【问题标题】:Extract specific information from file C++从文件 C++ 中提取特定信息
【发布时间】:2015-09-08 14:06:41
【问题描述】:

我正在尝试使用 c++ 读取文件,但我只想存储某些内容。这就是我的文件的样子

stufff
stuff
more stuff
    .
    .
    .
data_I_want 32 34 45
data_I_want 52 22 34
stuff again
    .
    .
    .
end of file

到目前为止我已经写了这段代码,但是输出总是0。

ifstream file;
file.open("stuff.txt");
string line;
double v;
if(file.is_open()){
    while(getline(file,line) && line.compare("data_I_want")){
            file>>v;
            cout<<v<<endl;
    }
    file.close();
}

【问题讨论】:

标签: file store ifstream getline


【解决方案1】:

行是 data_I_want 32 34 45,而不仅仅是 data_I_want。可能你想找到以 data_I_want 开头的行

下面是你如何使用 get substring of a string(取自here):

// string::substr
#include <iostream>
#include <string>

int main ()
{
  std::string str="We think in generalities, but we live in details.";
                                           // (quoting Alfred N. Whitehead)

  std::string str2 = str.substr (12,12);   // "generalities"

  std::size_t pos = str.find("live");      // position of "live" in str

  std::string str3 = str.substr (pos);     // get from "live" to the end

  std::cout << str2 << ' ' << str3 << '\n';

  return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 2023-03-28
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多