如何从具有多个类型的单行文件中只读取一个类型



所以我有一个文本文件,其中只有一行看起来像这样:

Steve 3 Sylvia 7 Craig 14 Lisa 14 Brian 4 Charlotte 9 Jordan 6

我要做的是从文本文件中读取每个整数。我试过一些代码,看起来像这个

#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int a;
ifstream inStream;
inStream.open("file.txt");
// case for file open failing
if ( inStream.fail() )
{
cout << "File open failed.n";
exit(1);
}
//attempting to read each integer and print it to see if it worked right
while( inStream.good() )
{
inStream>>a;
cout<<a;
}

return 0;
}

我知道当整个文件只由整数组成时,或者如果整个文件不是一行,这很简单,但我在这种情况下遇到了的问题

如果您知道格式将类似于名称编号名称编号。。。然后你可以做这样的事情:

int a;
string name;
// read name first then number
while( inStream >> name >> a )
{
cout << a << endl;
}

使用>阅读时不能跳过这些名称,但您可以阅读它们而不使用它们。

基本的正则表达式搜索可以有效地解决问题

#include <iostream>
#include <regex>
#include <string>
int main(int argc, const char** argv) {
std::string buf = "Steve 3 Sylvya 7 Craig 14 Lisa 14 Brian 4 Charlotte 9 Jordan 6";
std::regex all_digit("\d+");
std::smatch taken;
while(std::regex_search(buf, taken, all_digit, std::regex_constants::match_any)) {
for(auto x : taken)
std::cout << x << 'n';
buf = taken.suffix().str();
}
return 0;
}

请根据您的需要调整以上代码。使用从文件中获取的缓冲区切换字符串。

最新更新