C++文件的读取指定行

对于一个文件, 其中的数据排列如下

0,0 1 1 1 0 1 0 1

16,0 1 0 1 3 0 2 1

32,0 1 4 5 3 2 1 2

……

每一行最开始的数是坐标, 用来作为标示符, 请问如何根据这些坐标来读取坐标那一行坐标之后的那些数据然后存入数组之中

第1个回答  推荐于2016-03-25
#include <cstdio>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
vector <int> vec;
void Read(char *filename, int x)
{
ifstream obj_read;
obj_read.open(filename, ios::in);
string s;
while(!obj_read.eof())
{
getline(obj_read, s);
if(!s.empty())
{
char *pStart = (char *)s.c_str();
char *p;
int val;
p = pStart;
sscanf(p, "%d", &val);
if(val == x)
{
p = pStart;
while(*p!=',')
{
p++;
}
p++;
vec.clear();
while(*p)
{
while(!(*p>='0' && *p<='9'))
{
p++;
}
sscanf(p, "%d", &val);
vec.push_back(val);
while(*p>='0' && *p<='9')
{
p++;
}
}
break;
}
}
}
obj_read.close();
}
int main()
{
Read("data.txt", 16);
int i;
for(i=0;i<vec.size();i++)
{
cout << "vec[" << i << "] = " << vec[i] << endl;
}
return 0;
}追问

这个函数里的参数只定义了坐标的x位置吧, 在main函数里对于16,0和16,16这种坐标就会出现问题了吧.

追答

你就不能举一反三 改一改?,收个税

本回答被提问者和网友采纳
第2个回答  2020-04-02
好像没有特别好的办法,我能想到的是用gets接口一行一行的读,前6次读取后扔掉不要,只保留第七次gets的结果
相似回答