bitset<N>* read_graph(string filepath)
{
FILE *fp;
char line[100];
bitset<N> bs[N];
fp = fopen(filepath.c_str(), "r");
if(fp != NULL)
{
while(!feof开发者_运维百科(fp))
{
fgets(line, 100, fp);
//cout << line << endl;
if(line[0] == 'a')
{
string str = "";
int i(0);
for(i = 2; line[i] != ' '; i++)
{
if(line[i] != ' ')
{
str += line[i];
}
}
int fi = atoi(str.c_str());
i++;
str = "";
for(int j = i; line[j] != ' '; j++)
{
if(line[j] != ' ')
{
str += line[j];
}
}
int si = atoi(str.c_str());
si--;
fi--;
//cout << "string: " << str << endl;
cout << "fi: " << fi;
//cout << "string: " << str << endl;
cout << " si: " << si << endl;
bs[fi][si]= 1;
}
}
}
fclose(fp);
return bs;
}
The outcome is the following (fi stands for first index and si stands for second index):
sample.gr
fi: 0 si: 1 fi: 0 si: 2 fi: 1 si: 3 fi: 2 si: 4 fi: 3 si: 2 fi: 3 si: 5 fi: 4 si: 1 fi: 4 si: 5 fi: 4 si: 5000000
000001 011000 001000 000000 000000
The indexes are right, I've checked them, but the matrix should be the following (it is mirrored because of the bitset's right side positioning):
000000
010001 001001 000010 000100 011000
I guess the error is somewhere around the bitset element accessing but I cannot find out what exactly is wrong.
I appreciate any help. Thanks.
With the pointer to a local array problem fixed, your code runs for me and prints what's expected (except mirrored).
But wouldn't it be easier to use C++ I/O in this case?
#include <vector>
#include <bitset>
#include <iterator>
#include <fstream>
#include <sstream>
#include <iostream>
const int N=6;
std::vector<std::bitset<N> > read_graph(const std::string& filepath)
{
std::vector<std::bitset<N> > bs(N);
std::ifstream fp(filepath.c_str());
for(std::string line; getline(fp, line); )
{
if(line.size() > 1 && line[0] == 'a')
{
std::istringstream str(line.substr(1));
int fi, si;
str >> fi >> si;
std::cout << "fi: " << fi << " si: " << si << '\n';
bs[--fi][--si]= 1;
}
}
return bs;
}
int main()
{
std::vector<std::bitset<N> > v = read_graph("sample.gr");
copy(v.rbegin(), v.rend(),
std::ostream_iterator<std::bitset<N> >(std::cout, "\n"));
}
test run: https://ideone.com/z7Had
You are returning a pointer to a local array. Undefined Behavior.
Use a vector<bitset<N> >
or similar instead.
精彩评论