1

Possible Duplicate:
Splitting a string in C++

I'm working on an assignment for my C++ class and I was hoping I could get some help. One of my biggest problems in coding with C++ is parsing strings. I have found longer more complicated ways to parse strings but I have a very simple program I need to write which only needs to parse a string into 2 sections: a command and a data section. For instance: Insert 25 which will split it into Insert and 25.

I was planning on using an array of strings to store the data since I know that it will only split the string into 2 sections. However I also need to be able to read in strings that require no parsing such as Quit

What is the simplest way to accomplish this without using an outside library such as boost?

Community
  • 1
  • 1
triple07
  • 63
  • 9

4 Answers4

2

The simplest may be like this:

string s;
int i;

cin >> s;
if (s == "Insert")
{
    cin >> i;
    ... // do stuff
}
else if (s == "Quit")
{
    exit(0);
}
else
{
    cout << "No good\n";
}

The simplest way may be not so good if you need e.g. good handing of user errors, extensibility etc.

anatolyg
  • 26,506
  • 9
  • 60
  • 134
1

You can read strings from a stream using getline, and then to a split by finding the firs position of a space character ' ' within the string, and using the substr function twice (for the command to the left of the space and for the data to the right of space).

while (cin) {
     string line;
     getline(cin, line);
     size_t pos = line.find(' ');
     string cmd, data;
     if (pos != string::npos) {
         cmd = line.substr(0, pos-1);
         data = line.substr(pos+1);
     } else {
         cmd = line;
     }
     cerr << "'" << cmd << "' - '" << data << "'" << endl;
}

Here is a link to a demo on ideone.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

This is another way :

string s("Insert 25");
istringstream iss(s);
do
{
   string command; int value;
   iss >> command >> value;
   cout << "Values: " << command << " " << values << endl;
} while (iss);
Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
0

I like using streams for such things.

int main()
{
    int Value;
    std::string Identifier;
    std::stringstream ss;
    std::multimap<std::string, int> MyCollection; 

    ss << "Value 25\nValue 23\nValue 19";

    while(ss.good())
    {
            ss >> Identifier;
            ss >> Value;
            MyCollection.insert(std::pair<std::string, int>(Identifier, Value));
    }

    for(std::multimap<std::string, int>::iterator it = MyCollection.begin(); it != MyCollection.end(); it++)
    {
            std::cout << it->first << std::endl;
            std::cout << it->second << std::endl;
    }

    std::cin.get();
    return 0;
}

This way you can allready convert your data into the needed format. And the stream automatically splits on whitespaces. It works the same way with std::fstream if your working with files.

roohan
  • 731
  • 3
  • 8
  • 15