0

I am new at the graph section. I recently tried to write program which will take number of vertices , edges and the connections between vertices.

#include<iostream>
#include<queue>
#include<vector>

using namespace std ;

void add_edge(vector<int> adj[] , int v1 , int v2 )
{
    adj[v1].push_back(v2);
    adj[v2].push_back(v1);
}

void print_graph ( vector<int>adj[] , int vertices)
{
    for(int i = 0 ; i < vertices ; i++)
    {
        cout<< "adjacency list of vertex " << i << " is : \n" ;
        cout<< "head -> " ;
        for(auto it = adj[i].begin() ; it != adj[i].end() ; it++)
        {
            cout << *it << " -> " ;
        }
        cout<< "\n" ;
    }
}
int main()
{
    int ver , ed , i , j , s , v1 , v2 , temp ;
    cin >> ver >> ed ;
    vector<int> adj[ver] ;
    for(i = 0 ; i < ver ; i++)
    {
        cin>> v1 ;
        for(i = 0 ; i < ed ; i++)
        {
            cin >> v2 ;
            char ch = (char)v2 ;
            if (v2 == '\n')
            {
                break ;
            }
            add_edge(adj , v1 , v2 ) ;
        }
    }

    print_graph(adj , ver);

return 0 ;
}

I was confused about how to stop the loop when the user presses enter . So I tried this. Doesn't look so cool but logical in my opinion.

   cin >> v2 ;
   char ch = (char)v2 ;
    if (v2 == '\n')
     {
         break ;
     }

But the complete program is not working properly. Please help me to figure out.

1 Answers1

0

You are using the variable i for two loops. After the inner for loop, i will always be equal to ed, and if that is smaller than ver, you're in an endless loop.

Use a different variable for the inner loop, e.g. the j you already defined:

for (j = 0; j < ed; j++)

Also note that while you are allowed to compare v2 to '\n', this does not check whether the user pressed enter. Instead, you're comparing v2 with the ASCII value of the linefeed character (i.e. 10). You can change separators, e.g. to only stop input at a newline character, see this question.

flyx
  • 35,506
  • 7
  • 89
  • 126
  • Just tell me what to do when I have to break the loop by pressing enter. – MD.Maruf Hasam Dec 12 '19 at 01:45
  • @MD.MarufHasam You need to describe in more detail what you want to do. With my fix, the for loops will break automatically when the specified number of vertices and edges have been entered. If you want to break on enter, why are you initially asking for the number of vertices and edges? – flyx Dec 12 '19 at 09:03