从文件中提取特定信息 C++
Extract specific information from file C++
我正在尝试使用 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();
}
行是 data_I_want 32 34 45,而不仅仅是 data_I_want。可能您想查找以 data_I_want
开头的行
下面是如何使用获取字符串的子字符串(取自 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;
}
我正在尝试使用 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();
}
行是 data_I_want 32 34 45,而不仅仅是 data_I_want。可能您想查找以 data_I_want
开头的行下面是如何使用获取字符串的子字符串(取自 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;
}