How to select parts of sentences in strings (C++)

Viewed 119

I am making a command line program, and I was wondering how to get different parts of sentences, so lets say if someone entered cd Windows/Cursors, it would detect (with an if statement) that they entered cd and then (in that same if statement) it would select the rest of the sentence, and set that as the directory. This is my code:

#include "stdafx.h"
#include <string>
#include <iostream>

using namespace std;
int main()
{
    while (1)
    {
        string directory = "C:/";
        string promptInput;
        string afterPrint;
        string prompt = "| " + directory + " |> ";
        cout << prompt;
        cin >> promptInput;

        if (promptInput == "") 
        {

        }
        else if (promptInput == "h:/")
        {
            directory = "H:/";
        }
        if (promptInput != "") {
            cout << "    " << afterPrint << "\n";
        }
    }
    return 0;
}

I haven't tried anything yet, so I am open to suggestions.

Help will be highly appreciated.

-Caleb Sim

2 Answers

You can use std::stringstream to read each line and convert it to stream. Then break the line in to separate parts, create a response based on the first word in the line. For example:

#include <sstream>
...
int main()
{
    string line;
    while(getline(cin, line))
    {
        stringstream ss(line);
        string cmd;
        if(ss >> cmd)
        {
            if(cmd == "cd")
            {
                string dir;
                if(ss >> dir)
                {
                    cout << "changedir: " << dir << "\n";
                }
            }
            else if(cmd == "c:" || cmd == "c:\\")
            {
                cout << "changedir: " << cmd << "\n";
            }
            else
            {
                cout << "error\n";
            }
        }
    }
    return 0;
}

The generic answer depends on your problem set, but a specific answer for your example could look as follows:

else if (promptInput == "cd")
{
     std::string directory;
     std::getline(std::cin, directory);
     ChangeDirectory(directory);
}
Related