Reputation: 97
int main()
{
char line[100];
int N = 5;
vector<int>adj[N];
FILE *in = fopen("test.txt", "r");
for (int i = 1; i <= N; i++)
{
fgets(line, 100, in);
char *pch = strtok(line, "\t \n");
int u = atoi(pch);
pch = strtok(NULL, "\t \n");
while (pch != NULL)
{
int v = atoi(pch);
adj[u].push_back(v);
pch = strtok(NULL, "\t \n");
}
}
for( int i = 0 ; i < 5; i++ ) // Printing graph
{
for( int p = 0 ; p < adj[i].size(); p++ )
{
cout<< i << " , "<< adj[i][p]<<endl;
}
}
Here "test.txt" file contains the data like this
1 2 3
2 1 4 5
3 1
4 2
5 2
First column contains the vertices ( 1 - 5 )
1 2 3
Above row ( first row ) means , Node 1
is connected to Node 2
and Node 3
2 1 4 5
Above row ( 2nd row ) means , Node 2
is connected to Node 1
, Node 4
and Node 5
I want to read this data as a Graph. And then needs to print the Graph.
I am expecting the output as this
1,2
1,3
2,1
2,4
2,5
3,1
4,2
5,2 // not getting in output
But I am not getting Node 5 in output. I tried some other data but still last node I can not see in output.
It will be great, if anyone helped me.
Upvotes: 0
Views: 790
Reputation: 18480
vector<int>adj[N+1]; //change this line also
for( int i = 1 ; i <= 5; i++ ) // Printing graph
Change this line .
Upvotes: 2
Reputation: 161
R Sahu has the right answer, you have an off-by-one error.
I would add that you should use c++ features to avoid this kind of errors.
Hence replacing your vector<int> adj[N];
with vector<vector<int>> adj;
or array<vector<int>>
.
Then you can use at to access your data (by ref) and catch a nice runtime error to detect your defect.
Upvotes: 1
Reputation: 206667
The line
adj[u].push_back(v);
accesses memory using an out of bounds index when u
is 5. That is cause for undefined behavior. It needs to be:
adj[u-1].push_back(v);
There is also a parsing error with your code when there are whitespace characters after the numbers in a line. You can avoid the pitfalls of parsing a line using strtok
by using std::istringstream
. Here's my suggestion:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <cstdlib>
using namespace std;
int main()
{
const int N = 5;
vector<int> adj[N];
std::ifstream infile("socc.in");
std::string line;
int i = 0;
while ( i < N && getline(infile, line) )
{
std::istringstream str(line);
int u;
str >> u;
if ( u > N )
{
// Problem.
abort();
}
int v;
while ( str >> v )
{
adj[u-1].push_back(v);
}
++i;
}
for( int i = 0 ; i < N; i++ ) // Printing graph
{
for( size_t p = 0 ; p < adj[i].size(); p++ )
{
cout<< i << " , "<< adj[i][p]<<endl;
}
}
}
Upvotes: 2