我如何从具有多种类型的单行文件中仅读取一种类型?

问题描述 投票:0回答:1

所以我有一个单行的文本文件,看起来像这样:

[[史蒂夫3西尔维亚7克雷格14丽莎14布莱恩4夏洛特9乔丹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; }

我知道当整个文件仅由整数组成,或者如果整个文件不是一行时,这很简单,但是在这种情况下我遇到了麻烦
c++ stdio
1个回答
1
投票
如果您知道格式类似于

名称号码名称号码 ...那么您可以执行以下操作:

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

>>

进行阅读时,您不能跳过名称,但可以阅读而对它们不做任何事情。
© www.soinside.com 2019 - 2024. All rights reserved.