Home > Enterprise >  C Program is not entering "for" loop
C Program is not entering "for" loop

Time:10-27

I am making a program that finds how many anagrams does a line contain for homework and I have a problem. My program is not entering a simple "for" loop. I've been reading whole evening and I cannot understand what is the problem. I've put 7 control cout-s to see where exactly does it enter and where not. Results are - 1, 2, 3 ,7 - not even entering the "for" loop. What could be the problem? Here is my code:

#include<iostream>
#include<string>
#include <sstream>
#include<vector>
#include <algorithm>
using namespace std;
bool isAnagram(string x, string y)
{
    vector<char>v;
    int szX = x.size(), szY = y.size();
    for (int i = 0; i < szX; i  )
    {
        if (!(find(v.begin(), v.end(), x[i]) != v.end()))
        {
            v.push_back(x[i]);
        }
    }
    for (int j = 0; j < szY; j  )
    {
        if (!(find(v.begin(), v.end(), y[j]) != v.end()))
        {
            return false;
        }
    }
    return true;
}

void breakStringToWords(string str, vector<string> w)
{
    istringstream ss(str);
    string word;
    while (ss >> word)
    {
        w.push_back(word);
    } 
}

int main()
{ 
    string x;
    vector<string>v;
    int cnt=0,sz;
    while(getline(cin, x))
    {
        if(x=="")
        {
            return 0;
        }
        cout<<1<<endl;
        breakStringToWords(x, v);
        cout<<2<<endl;
        sz=v.size();
        cout<<3<<endl;
        for(int i=0; i<sz; i  )
        {
            cout<<4<<endl;
            if (isAnagram(v[i - 1], v[i]))
            {
                cout<<5<<endl;
                cnt  ;
            }
            cout<<6<<endl;
        }
        cout<<7<<endl;
        cout<<cnt<<endl;
    }
    return 0;
}

Thank you in advance!

CodePudding user response:

Here is one error:

void breakStringToWords(string str, vector<string> w)

You are passing w by value, meaning that the breakStringToWords function is working with a temporary vector. As soon as that function returns, w no longer exists.

You should pass by reference, not by value: void breakStringToWords(string str, vector<string>& w) // Note the &

It is no different than doing something like this:

#include <iostream>
void foo(int x)
{
  x = 10;
}

int main()
{
  int x = 0;
  foo(x);
  std::cout << x; // x is still 0, not 10
}

Same issue, same solution -- pass by reference.

CodePudding user response:

Re:

It entered the loop and threw another exception

when i is 0, you are accessing v[-1]:

    for(int i=0; i<sz; i  )
    {
        cout<<4<<endl;
        if (isAnagram(v[i - 1], v[i]))
  • Related