Search code examples
c++fstream

Ignoring ALL parts of a string before a space


I'm writing a small chat-bot program in C++

Right now I have functionality for the robot to write whatever the user says to a file brain.txt, and places a number next to it in the file in order of when it was remembered. Continuing on, entering the userinput Grapefruit would put grapefruit on a new line, and a 6 as a prefix.

0 suspect
1 interest
2 underwood
3 interior
4 bullet
5 dog

I've ran into an issue where I need to compare the userinput with a memory the bot already has from previous userinput's.

ifstream brain ("projects/AI/brain.txt");
if (brain.is_open())
{
    while ( getline(brain,memory))
    {
        cout << "memory: " << memory << endl; 
        cout << "userinput: " << userinput << endl; 
        if (memory == userinput)
            {
                exists = true;
                //if it exists, tell the user, and break
                cout << "I know that already!" << endl;
                break;
            }
        else { filepos++; }

If the userinput was grapefruit the bot's memory is 6 grapefruit ergo if it was comparing these two the comparison check would fail, as they're not the same string.

I want numbers to remain a part of the string and for me to be able to selectively choose parts of the string to read. I may upgrade to JSON or something similar later, but for right now, this is the way I'd like to do this.

  • my first question is, how can i ignore ALL of the string until after a space? so my program will correctly compare grapefruit and grapefruit instead of 6 grapefruit

  • my second question is, can I expand this functionality so that I can skip multiple spaces and only read after multiple spaces have passed?

for example, in the string: 6 Grapefruit 23 53 12 I want to access the number 53, and nothing else.

Ways to improve this and ways I've maybe done this incorrectly?

I could've lifted this into say, a vector of tuples or something at runtime at program startup and that stops me from accessing from a file. This is something I may do in the future.


Solution

  • If your strings are stored in std:string objects, you can use the find method() to determine in the input string is contained by the memory string.

    http://en.cppreference.com/w/cpp/string/basic_string/find

    if (memory.find(userinput) != std::string::npos)
    {
                    exists = true;
                    //if it exists, tell the user, and break
                    cout << "I know that already!" << endl;
                    break;
    }
    

    std::string:npos is defined as a special character that in this case signifies that no match was found before the end of the string.

    http://en.cppreference.com/w/cpp/string/basic_string/npos