-2

I'm having trouble with an assignment, and I searched all over stack and google but can't figure out the issues.

Right now, the only code I have so far is to ask user to put in a sentence and then breaks the sentence into different strings. And I also need to compare it to a text file which I halfway got.

First problem: My method of splitting up the words into different strings only works sometimes. For example when I write "history people" it tells me theres a segmentation fault, but if I type in "history people " (with the space at the end), it works fine. I'm confused what the problem is.

The 2nd problem is that I can't figure out how to compare my string to the text file line by line, it seems to store the whole file into my string variable "text".

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int noun(string n)
{
    ifstream inputfile;
    bool found = false; // set boolean value to false first
    string text;
    inputfile.open("nouns"); // open text file
    if (!inputfile.is_open()) 
    { // checks to make sure file is open
        cout << "Error" << endl;
    }

    while (getline(inputfile,text,' ')) 
    {
        if (n == text)
        {
            found = true;
            cout << text;
        } 
    }
    inputfile.close(); // close the file
    return found; // return true or false
}

int main ()
{
    string sent;
    string word1, word2, word3, word4; // strings to parse the string 'sent'
    cout << "Please enter a sentence" << endl;
    getline (cin, sent);

    int w1, w2, w3, w4 = 0; // positions in relation to the string
    while (sent[w1] != ' ')
    { // while loop to store first word
        word1 += sent[w1];
        w1++;
    }

    w2 = w1 + 1;
    while (sent[w2] != ' ')
    { // while loop to store second word
        word2 += sent[w2];
        w2++;
    }

    w3 = w2 + 1;
    while (sent[w3] != ' ')
    { // while loop to store 3rd word
        word3 += sent[w3];
        w3++;
    }

    w4 = w3 + 1;
    while (sent[w4] != sent[-1])
    { // while loop to store 4th word
        word4 += sent[w4];
        w4++;
   }

    cout << word1;

    if (sent.empty())
    { // empty set returns "invalid sentence"
        cout << "Invalid Sentence" << endl;
    }
    else if (noun(word1) == true)
    {
        cout << "This is valid according to rule 1" << endl; 
    }

    return 0;
}
muXXmit2X
  • 2,745
  • 3
  • 17
  • 34
HCL212
  • 3
  • 5
  • another thing i forgot to mention, if i just write the word "history" it prints out "history!" idk where the exclamation mark is coming from – HCL212 Mar 13 '17 at 06:59
  • Why don't you just `cin >> word1; cin >> word2; ...`? – SingerOfTheFall Mar 13 '17 at 07:04
  • 1
    Please [edit] your code to reduce it to a [mcve] of your problem. Your current code includes much that is peripheral to your problem - a minimal sample normally looks similar to a good unit test: only performing one task, with input values specified for reproducibility. – Toby Speight Mar 13 '17 at 10:01
  • @TobySpeight Thanks, I will keep in mind for next time. – HCL212 Mar 13 '17 at 16:38

1 Answers1

1

when I write "history people" it tells me theres a segmentation fault, but if I type in "history people " (with the space at the end), it works fine

Well easy. Your while loop runs over the string until it finds a space. But what if there is no space? Does the loop terminates then? Nope - It will continue until it eventually finds a space character somewhere in memory or crashes or something else (It's undefined behavior so basically everything can happen, also appending an exclamation mark at the end of your output). How to fix that? Check whether you're at the end of the string.

while (sent[w1] != ' ' && w1 < sent.size()) ...

or use a completely different approach to split the string in the first place (Have a look at this answer here).

To the second problem. Reading from the file looks okay to me, but without knowing how the content of the file looks I can't really help you.

According to your code I'd expect the file to look somewhat like that:

noun1 noun2 noun3 noun4 etc.

since you set the delimiter of getline to be a space: getline(inputfile, text, ' '). This would mean that that all the nouns in the file are separated by a space and listed all in one line. Is this the case? No? Well then just change the delimiter to be the correct delimiter you're using in the file itself. (Btw. If each noun is listed in a separate line you don't need to specify a delimiter getline(inputfile, text))

Also if you check whether the file could not be opened then don't continue reading but stop the execution of that function.

if (!inputfile.is_open()) { // checks to make sure file is open
    cout << "Error" << endl;
    return false; // return for example or throw an exception
}

Yet there are still other problems with your application, e.g. check the user input before processing it and you don't need to close an ifstream its destructor takes care of that.

Or what do you think int w1, w2, w3, w4 = 0 does? Setting all the variables to 0? Guess what, no. w4 is initialized and set to 0 but all the other values are uninitialized and anywhere using them again invokes UB. So this sent[w1] is undefined behavior, this w1++ is, this w2 = w1 + 1 is, and ...

Be always sure and do it the right way. One line per variable declaration and directly initialize them.

int w1 = 0;
int w2 = 0;
int w3 = 0;
int w4 = 0;

Also have you ever heard of the DRY principle? Your 4 while loops look kind of similar, don't they? You could write a function to do that and then call it 4 times (or as I said before, use a completely different approach).

Community
  • 1
  • 1
muXXmit2X
  • 2,745
  • 3
  • 17
  • 34
  • Thanks for the advice, I just figured out that the comparing to text file function is fine, but its my loops trying to parse the original sentence thats causing problems. We're not allowed to use vectors and arrays which is why I'm having a hard time figuring this out. – HCL212 Mar 13 '17 at 15:42
  • actually your comment just helped me click it in my head, thanks so much! I was trying to wrap this around my brain for hours last night! thanks again! – HCL212 Mar 13 '17 at 15:50
  • Glad I could help ;) – muXXmit2X Mar 13 '17 at 16:08