//my program should be able to collect two words and compare them outputing the words from word1 which are also in word2 and outputing them and viceversa. my problem is in the last four lines before the return. Please help

//Program to shows analysis of texts
#include <iostream>      // for cin, cout
#include <string>
#include <iomanip>

using namespace std;

int main()
{
    string word1, word2;        //declaration of words

    // Welcome message 
    cout<< "------------------------------------------------\n"
        << "    Topiloe's Text analyzer - Release 1.0  \n"
        << "------------------------------------------------\n\n";

    cout<<"Enter two words on one line: ";
    cin>>word1>>word2;
    cout<<"Second word you entered is <"<<word2<<"> \n";
    cout<<"It is "<<word2.length()<<" characters long\n";
    cout<<"Starts with the letter '"<<word2.substr(0,1)<<"'\n";
    int last_word;
    last_word=word2.length()-1;
    cout<<"Ends with the letter '"<<word2.substr(last_word,1)<<"'\n\n";

    cout<<"First word you entered is <"<<word1<<"> \n";
    cout<<"It is "<<word1.length()<<" characters long\n";
    cout<<"Starts with the letter '"<<word1.substr(0,1)<<"'\n";
    last_word=word1.length()-1;
    cout<<"Ends with the letter '"<<word1.substr(last_word,1)<<"'\n\n";

    cout<<"The leters in <"<<word1<<"> which are also in <"<<word2<<"> are"<<word1.find(word2)<<endl;
    cout<<"There are "<<word1.find(word2)<<" words in "<<word1<<" which are also in "<<word2<<endl;

    cout<<"The leters in <"<<word2<<"> which are also in <"<<word1<<"> are"<<word2.find(word1)<<endl;
    cout<<"There are "<<word2.find(word1)<<" words in "<<word2<<" which are also in "<<word1<<endl;

    return 0;

}

string.find looks for the entire substring provided (as a whole) within the string it is called on. It returns the position of the start of that substring within the original string.

It seems that you are trying to find individual letters that are common between two strings (if I understand your description/code correctly). What you really want, then, is to find the intersection of the two strings.

Your assignment states "Write a program in java " exercise 2, are you sure you want it in c++ ?

I just saw the Java. It should be C++

Edited 2 Years Ago by Ezekiel_1: Update

This is what I have now but the output is not proper yet. The output of the characters should be on the same line. The second part is also showing integers and not characters

/Program to shows analysis of texts
#include <iostream>      // for cin, cout
#include <string>
#include <iomanip>

using namespace std;

int main()
{
    string word1, word2;        //declaration of words

    // Welcome message 
    cout<< "------------------------------------------------\n"
        << "    Topiloe's Text Analyzer - Release 1.0  \n"
        << "------------------------------------------------\n\n";

    cout<<"Enter two words on one line: ";
    cin>>word1>>word2;
    cout<<"Second word you entered is <"<<word2<<"> \n";
    cout<<"It is "<<word2.length()<<" characters long\n";
    cout<<"Starts with the letter '"<<word2.substr(0,1)<<"'\n";
    int last_word;
    last_word=word2.length()-1;
    cout<<"Ends with the letter '"<<word2.substr(last_word,1)<<"'\n\n";

    cout<<"First word you entered is <"<<word1<<"> \n";
    cout<<"It is "<<word1.length()<<" characters long\n";
    cout<<"Starts with the letter '"<<word1.substr(0,1)<<"'\n";
    last_word=word1.length()-1;
    cout<<"Ends with the letter '"<<word1.substr(last_word,1)<<"'\n\n";

    for(int i = 0; i < word1.length(); i++)
    {
        for(int j = 0; j < word2.length(); j++)
        {
            if(word1[i] == word2[j])  //letter matched
                {
                    cout<<"The leters in <"<<word1<<"> which are also in <"<<word2<<"> are "<<word1[i]<<"\n";
                }
        }
    }
    cout<<"There are "<<word1.find(word2)<<" letters in "<<word1<<" which are also in "<<word2<<endl;

    for(int i = 0; i < word2.length(); i++)
    {
        for(int j = 0; j < word1.length(); j++)
        {
            if(word2[i] == word1[j])  //letter matched
            {
                cout<<"The leters in <"<<word2<<"> which are also in <"<<word1<<"> are "<<word2.find(word2[i])<<"\n";
            }
        }
    }
    cout<<"There are "<<word2.find(word1)<<" letters in "<<word2<<" which are also in "<<word1<<endl;

    cout<<"Thank you for using Topiloe Text Analyzer\n";
    return 0;

}

Actually, it does say Java, in the second assignment description. I suspect, however, that it was an error - my guess is, they use the same basic assigment in both the C++ and Java courses, and the instructor made a mistake when editing the assignment.

As far as formatting goes, create a function call "space"

string space(int numSpaces)
{
    string mySpace;

    for (int i=0; i < numSpaces; i++)
    {
        mySpace += " ";
    }//for

    return mySpace;
}//

To use it: cout << space(9)

Change line 20 (and some of the other ones) to:

cout<< space(9) << "It is "<<word2.length()<<" characters long\n";

In line 38, move most of the output line outside of the for loops (to line 31):

cout<<"The leters in <"<<word1<<"> which are also in <"<<word2<<"> are:" << endl;

Line 38 becomes:

cout << word1[i] << space(1);

Put the following after the for loop (after line 41):

cout << endl;

Edited 2 Years Ago by cgeier

Comments
I have actually used \t to create the tab. I wanted to get the codes right before formatting. thanks
string spc( 3, ' ' );
cout << '*' << spc << '*';

Is short code ...

But ... what is a 'word' ? Does it need to be a real word that is in the English dictionary? If so ... that is NOT what you are doing.

See this for starters on a dictionary lookup for your words ...

// twoWords.cpp //  // 2014-02-24 //

// program to be able to take in two words and
// compare them ... outputing the words from word1 which
// are also in word2 and ... vice-versa.

#include <iostream> // for cin, cout
#include <vector>
#include <string>
#include <iomanip>
#include <algorithm> // re. find

using namespace std;

typedef vector< string > VecStr;

char takeInChar( const string& msg )
{
    cout << msg << flush;
    string reply;
    getline( cin, reply );
    if( reply.size() )
        return reply[0];
    // else ...
    return 0;
}
bool more()
{
    if( tolower( takeInChar( "More (y/n) ? " )) == 'n' )
        return false;
    // else ...
    return true;
}


int main()
{
    string word1, word2; //declaration of words

    // Welcome message
    cout << "------------------------------------------------\n"
         << " Topiloe's Text Analyzer - Release 1.0 \n"
         << "------------------------------------------------\n\n";

    cout << "Enter two words on one line (separated by a space): ";
    cin >> word1 >> word2;

    string dummy;
    getline( cin, dummy ); // eat '\n', etc... that's still at end of cin stream

    cout << "The words entered were: " << word1 << ", " << word2 << '\n';

    VecStr vs1, vs2; // construct two empty vectors ...

    // instead of a dictionary lookup ... do 'intelligent selections' for now
    string word;
    do
    {
        cout << "Enter next word found in word 1: " << flush;
        cin >> word;
        getline( cin, dummy ); // eat '\n', etc... that's still at end of cin stream

        vs1.push_back( word );
    }
    while( more() );

    do
    {
        cout << "Enter next word found in word 2: " << flush;
        cin >> word;
        getline( cin, dummy ); // eat '\n', etc... that's still at end of cin stream

        vs2.push_back( word );
    }
    while( more() );


    VecStr::const_iterator it1, it2;
    cout << "Words in word 1 found in word 2:\n";
    for( it1 = vs1.begin(); it1 != vs1.end(); ++it1 )
    {
        it2 = find( vs2.begin(), vs2.end(), *it1 );
        if( it2 != vs2.end() )
            cout << *it2 << ' ';
    }
    cout << endl;

    cout << "Words in word 2 found in word 1:\n";
    for( it2 = vs2.begin(); it2 != vs2.end(); ++it2 )
    {
        it1 = find( vs1.begin(), vs1.end(), *it2 );
        if( it1 != vs1.end() )
            cout << *it1 << ' ';
    }
    cout << endl;

    cout << "\nThank you for using Topiloe Text Analyzer. ";
    cin.sync(); // 'flush' cin stream ...
    cin.get();
    return 0;
}

Edited 2 Years Ago by David W: fixed spelling

Comments
The words I meant are the strings that will be entered by the user

I think that "compare them outputing the words from word1 which are also in word2 and outputing them and viceversa" is not what the assignment asks for. According to the syllabus, the assignment is to "display the letters from the first word which are also in the second word as well as the number" and "display the letters from the second word which are also in the first word as well as the number".

Here is code that gives the output as in the syllabus:

space:

    string space(int numSpaces)
    {
        string mySpace;

        for (int i=0; i < numSpaces; i++)
        {
            mySpace += " ";
        }//for

        return mySpace;
    }//

main:

int main()
{
        string word1, word2;        //declaration of words
        int  count = 0;
        bool letterFound = false;

    // Welcome message 
    cout<< "------------------------------------------------\n"
        << "    Topiloe's Text Analyzer - Release 1.0  \n"
        << "------------------------------------------------\n\n";

    cout << "Enter two words on one line: ";
    cin >> word1 >> word2;
    cout <<"Second word you entered is <" <<word2<< "> \n";
    cout << space(9) << "It is " << word2.length() << " characters long\n";
    cout << space(9) << "Starts with the letter '" << word2.substr(0,1) << "'\n";
    int last_word;
    last_word=word2.length()-1;
    cout << space(9) <<"Ends with the letter '" <<word2.substr(last_word,1) << "'\n\n";

    cout <<"First word you entered is <" << word1 << "> \n";
    cout << space(9) << "It is "<<word1.length() << " characters long\n";
    cout << space(9) << "Starts with the letter '"<< word1.substr(0,1) << "'\n";
    last_word=word1.length()-1;
    cout << space(9) << "Ends with the letter '"<< word1.substr(last_word,1) << "'\n\n";

    cout<<"The leters in <" <<word1 << "> which are also in <" << word2 << "> are:" << endl;
    for(int i = 0; i < word1.length(); i++)
    {
        letterFound = false;

        for(int j = 0; j < word2.length(); j++)
        {
            if(word1[i] == word2[j])  //letter matched
                {
                    if (letterFound == false)
                    {
                        cout << word1[i] << space(1);
                        //cout<<"The leters in <"<<word1<<"> which are also in <"<<word2<<"> are "<<word1[i]<<"\n";

                        letterFound = true;
                        count += 1;
                    }//if                   
                }
        }
    }
    cout << endl;
    cout<<"There are "<< count <<" letters in <" << word1 << "> which are also in <" <<word2 << ">" << endl;

    cout << endl;
    cout << "The leters in <" <<word2 << "> which are also in <" <<word1 << "> are" << endl;

    count = 0;
    for(int i = 0; i < word2.length(); i++)
    {
        letterFound = false;
        for(int j = 0; j < word1.length(); j++)
        {
            if(word2[i] == word1[j])  //letter matched
            {
                if (letterFound == false)
                {
                    cout << word2[word2.find(word2[i],i)] << space(1);
                    letterFound = true;
                    count += 1;
                }//if
            }
        }
    }
    cout <<  endl;

    cout<<"There are "<< count <<" letters in <" <<word2 << "> which are also in <" <<word1 << ">" << endl;
    cout << endl;
    cout<<"Thank you for using Topiloe Text Analyzer\n";


    return 0;
}

Although, I disagree with the correctness of the output on the syllabus (and the above code which gives the output on the syllabus). If I understand the assignment, a letter is unique (based on case). Therefore it shouldn't be printed out more than once or counted more than once. If there are two "n" then it should be only printed once and counted once. You may want to verify with your instructor.

Edited 2 Years Ago by cgeier

I have a good output now. I am pasting it for reference purpose. Thank you

//Program to shows analysis of texts
#include <iostream>      // for cin, cout
#include <string>
#include <iomanip>

using namespace std;

int main()
{
    string word1, word2;        //declaration of words

    // Welcome message 
    cout<< "------------------------------------------------\n"
        << "    Topiloe's Text Analyzer - Release 1.0  \n"
        << "------------------------------------------------\n\n";

    cout<<"Enter two words on one line: "; 
    cin>>word1>>word2;      //strings entered by the user to be analyzed
    cout<<"Second word you entered is <"<<word2<<"> \n";   //outputing the second word entered by user
    cout<<"\tIt is "<<word2.length()<<" characters long\n";
    cout<<"\tStarts with the letter '"<<word2.substr(0,1)<<"'\n";
    int last_word;  
    last_word=word2.length()-1;     //calculating the position for the last letter in the string
    int count_word1_in_word2 = 0, count_word2_in_word1 = 0;
    cout<<"\t with the letter '"<<word2.substr(last_word,1)<<"'\n\n";

    cout<<"First word you entered is <"<<word1<<"> \n";
    cout<<"\tIt is "<<word1.length()<<" characters long\n";   //outputing the second word entered by user
    cout<<"\tStarts with the letter '"<<word1.substr(0,1)<<"'\n";
    last_word=word1.length()-1;
    cout<<"\tEnds with the letter '"<<word1.substr(last_word,1)<<"'\n\n";
    cout<<"The leters in <"<<word1<<"> which are also in <"<<word2<<"> are \n";
    for(int i = 0; i < word1.length(); i++)
    {
        for(int j = 0; j < word2.length(); j++)
        {
            if(word1[i] == word2[j])  //letter matched
            {
                cout<<word1[i]<< " ";
                count_word2_in_word1++;
            }
        }
    }
    cout<<endl;
    cout<<"There are "<<count_word2_in_word1<<" letters in "<<word1<<" which are also in "<<word2<<endl;
    cout<<"The leters in <"<<word2<<"> which are also in <"<<word1<<"> are \n";
    for(int i = 0; i < word2.length(); i++)
    {
        for(int j = 0; j < word1.length(); j++)
        {
            if(word2[i] == word1[j])  //letter matched
            {
                cout<<word2[i]<<" ";
                count_word1_in_word2++;
            }
        }
    }
    cout<<endl;
    cout<<"There are "<<count_word1_in_word2<<" letters in "<<word2<<" which are also in "<<word1<<endl;

    cout<<"Thank you for using Topiloe Text Analyzer\n\n";
    return 0;

}

You may like to see this example ... that uses 'real words' found in some dictionary

// twoWords_dictionaryLookUp.cpp //  // 2014-02-25 //

// program to be able to take in two words and
// compare them ... outputing the words from word1 which
// are also in word2 and ... vice-versa.

// note: some debugging print-out info left-in ... in this version //


#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <set>       // to hold dictionaries (of words)
#include <algorithm> // re. find
#include <cctype>    // re. tolower

using namespace std;

#define DICT_FNAME "myDictionary.txt" //"infl.txt"

typedef set < string > Dict;


// parses out only words (from word) that are 2 letters or more ...
// that are IN the (big) Dict of words loaded in from file DICT_FNAME
void parseOutWords( const string& word, Dict& td, const Dict& d );

bool loadDictionaryFromFile( Dict& d );
void showDictionary( const Dict& d );

// utilities used here ...
void toAllLower( string& val )
{
    size_t len = val.size();
    while( len )
    {
        --len;
        val[len] = tolower( val[len] );
    }
}
char takeInChar( const string& msg )
{
    cout << msg << flush;
    string reply;
    getline( cin, reply );
    if( reply.size() )
        return reply[0];
    // else ...
    return 0;
}
bool more()
{
    if( tolower( takeInChar( "More (y/n) ? " )) == 'n' )
        return false;
    // else ...
    return true;
}



int main()
{
    Dict d;
    if( loadDictionaryFromFile( d ) )
    {
        string word1, word2; //construct two empty words

        // Welcome message
        cout << "---------------------------------------\n"
             << " Topiloe's Text Analyzer - Release 1.0 \n"
             << "---------------------------------------\n\n";

        do // main loop ...
        {
            bool isFound = false;
            do
            {
                cout << "Enter two words on one line (separated by a space): ";
                cin >> word1 >> word2;

                if( word1.size() < 2 || word2.size() < 2 )
                {
                    cout << "Words MUST BE at least 2 letters long.\n";
                    continue;
                }

                isFound = true;
                toAllLower( word1 );
                if( !d.count( word1 ))
                {
                    isFound = false;
                    cout << word1 << " NOT found in big dictionary used here.\n";
                }
                toAllLower( word2 );
                if( !d.count( word2 ) )
                {
                    isFound = false;
                    cout << word2 << " NOT found in big dictionary used here.\n";
                }

                string dummy;
                getline( cin, dummy ); // eat '\n', etc... at end of cin stream
            }
            while( !isFound );

            cout << "\nThe words you entered were: "
                 << word1 << ", " << word2 << "\n\n";


            Dict td1, td2; // construct two empty Dict's ...


            parseOutWords( word1, td1, d );
            cout << endl;
            parseOutWords( word2, td2, d );

            cout << "\nIn tmp Dict1, the words are:\n";
            showDictionary( td1 );
            cout << "\nIn tmp Dict2, the words are:\n";
            showDictionary( td2 );


            Dict::const_iterator it1, it2;
            cout << "\nWords in word1 found in word2:\n";
            for( it1 = td1.begin(); it1 != td1.end(); ++it1 )
            {
                it2 = find( td2.begin(), td2.end(), *it1 );
                if( it2 != td2.end() )
                    cout << *it2 << ' ';
            }
            cout << endl;

            cout << "Words in word2 found in word1:\n";
            for( it2 = td2.begin(); it2 != td2.end(); ++it2 )
            {
                it1 = find( td1.begin(), td1.end(), *it2 );
                if( it1 != td1.end() )
                    cout << *it1 << ' ';
            }
            cout << endl << endl;;

        }
        while( more() ); // main loop ends here ...

        cout << "\nThank you for using Topiloe Text Analyzer. ";
    }
    else cerr << "\nThere was a problem loading the big dictionary.\n";

    cout << "\nPress 'Enter' to continue/exit ... " << flush;

    cin.sync(); // 'flush' cin stream ...
    cin.get();
    return 0;
}


// restrict word length to be at least two letters long ...
// tmp Dict of words parsed out from word ... returned in Dict 'td'
void parseOutWords( const string& word, Dict& td, const Dict& d )
{
    for( size_t i = 0; i < word.size()-1; ++i ) // restrict word length to 2 letters or more
    {
        for( size_t len = word.size(); len >= 2; --len )
        {
            if( (len-i ) > 1 ) // don't allow, ONE letter words here ... //
            {
                string tmp = word.substr( i, len-i );
                cout << tmp << ' ';
                if( d.count( tmp ) ) { td.insert( tmp ); cout << "inserted, "; }
            }
        }
        cout << "inner ends" << endl;
    }
}

// all words stored as ALL lowercase letters ...
bool loadDictionaryFromFile( Dict& d )
{
    ifstream fin( DICT_FNAME );
    if( fin )
    {
        int i = 0;
        string word, line;
        while( getline( fin, line ) )
        {
            istringstream iss( line );
            iss >> word;

            toAllLower( word );
            d.insert( word );
            ++i;
            if( i == 1000 ) { cout << word << ' '; i = 0; }
        }
        fin.close();

        cout << "\nThere are now " << d.size()
             << " words in the dictionary.\n";
        return true;
    }
    cerr << "\nAn error ocured opening file " << DICT_FNAME << endl;
    return false;
}

void showDictionary( const Dict& d )
{
    Dict::const_iterator it;
    for( it = d.begin(); it != d.end(); ++it ) cout << *it << ' ';
    cout << "\nWord count = " << d.size() << " words." << endl;
}

Edited 2 Years Ago by David W

This article has been dead for over six months. Start a new discussion instead.