Home > Net >  Store substring between double quotes in cpp
Store substring between double quotes in cpp

Time:10-08

I am implementing the ALV tree, and I need to read input from the command line.

An example of the command is as follows:

insert “NAME_ANYTHING_IN_QUOTES_$” ID

where NAME_ANYTHING_IN_QUOTES_$ is the data being stored in the AVL tree, and ID is used to decide if the info will be stored in the left subtree or right subtree.

Code snipet is as follows:

if (comand == "insert")
{
    int ID = 0;
    string Name;
    cin >> Name;
    cin >> ID;
    root = insertInfo(root, Name, ID);
}

I can not figure out how to scan in the substring that is between two double-quotes.

Thanks.

CodePudding user response:

Use std::quoted:

std::string name;
std::cin >> std::quoted(name);

CodePudding user response:

I'm just adding to HolyBlackCat's answer above.
Here's code that works:

#include <iostream>
#include <iomanip>

using namespace std;


int main(int argc, const char** argv)
{
    //if (comand == "insert")
    {
        int ID = 0;
        string Name;
        cin >> std::quoted(Name);
        cin >> ID;
        cout << "name is " << Name << " and ID is " << ID << endl;  
        //root = insertInfo(root, Name, ID);
    }

}

When input is "MyName_$" 34
I get
name is MyName_$ and ID is 34
So, HolyBlackCat's solution works. Show us your code and input.

CodePudding user response:

On second thought, those strange open and close braces may depend on the font, etc. The std::quoted should have worked for you, but it you say it doesnt. Let us know what env and compiler you are using. If you're sure they're always there, you can just delete the first and last char in that string as in:

#include <iostream>
#include <string>

using namespace std;


int main(int argc, const char** argv)
{
    
    //if (comand == "insert")
    {
        int ID = 0;
        string Name;
        
        cin >> Name;

        Name.erase(0, 1);
        Name.erase(Name.length() - 1, 1);
                
        cin >> ID;

        cout << "name is " << Name << " and ID is " << ID << endl;
        
        //root = insertInfo(root, Name, ID);
    }

}
  • Related