-1

I'm reading a text file line by line with this code.

    fstream reader;
    string text;
    string readingArray[];
    int length2;

    while (getline(reader, text)) {
                readingArrray[lenght2]=text;
                lenght2++;

            }

While reading I've got a line ' SAY "Welcome to the jungle" '. And I want to seperate to two parts this line, like SAY and "Welcome to the jungle".

So I need; firstly the program should read the line until " character. After that program should read the part between " and \n characters. How can i do that?

Cœur
  • 37,241
  • 25
  • 195
  • 267
jesta
  • 61
  • 6
  • firstly convert the string to a char array, And then split it to two different char array, and then use them to initialize your two string object. Couldn't find an easy way to do it. –  Nov 11 '15 at 17:28
  • @SimonKraemer i m searching for a smaller way than this. –  Nov 11 '15 at 17:30
  • You can use std::string member function to find specific characters in your string. Once the characters positions are known, you can use the substr function to extract specific portions of the original string. – Anon Mail Nov 11 '15 at 17:30
  • What you are describing here is called "to tokenise a string". You will find an endless number of tutorials, questions, answers, example code and libraries with the search terms "string tokenise c++". – Christian Hackl Nov 11 '15 at 17:36
  • @KishanKumar Converting `std::string` to a char array is by far not the easiest way to do this. See my answer – Simon Kraemer Nov 11 '15 at 17:37
  • @SimonKraemer sorry my bad. Used to do this by that way. –  Nov 11 '15 at 17:39
  • Possible duplicate of [How to read string from file and tokenise it into an array?](http://stackoverflow.com/questions/17416800/how-to-read-string-from-file-and-tokenise-it-into-an-array) – Michael Shopsin Nov 11 '15 at 18:42

1 Answers1

1

Search for the first occurence of "(don't forget escaping it to \") using std::string::find

Then use std::string::substring to split your string.

Example:

int main()
{
    string line = "SAY \"Welcome to the jungle\"";
    size_t split_pos = line.find('\"');
    if (split_pos != string::npos) //No " found
    {
        string firstPart = line.substr(0, split_pos); //Beginning to result
        string secondPart = line.substr(split_pos);   //result to end

        cout << firstPart << endl;
        cout << secondPart << endl;
    }
}

Output:

SAY
"Welcome to the jungle"
Simon Kraemer
  • 5,700
  • 1
  • 19
  • 49
  • 2
    There's no need to escape the the double-quote in the character literal. `'"'` works. Arguably harder to read, but legal. – Nathan Ernst Jul 07 '17 at 15:05