3

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

Anonymous
  • 355
  • 2
  • 14
  • Unrelated: if you are using Visual Studio, and `#include "stdafx.h"` suggests this, put `#include "stdafx.h"` at the first thing in the file. Everything above it will be ignored. More here: https://stackoverflow.com/questions/2976035/purpose-of-stdafx-h. Why people put up with this smurf: https://stackoverflow.com/questions/4726155/whats-the-use-for-stdafx-h-in-visual-studio – user4581301 Nov 03 '17 at 05:06

2 Answers2

1

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;
}
Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77
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);
}
Ben
  • 2,867
  • 2
  • 22
  • 32