Search code examples
c++stringifstream

Splitting string into smaller strings from text input


Reading in a text file to a C++ program I'm working on, and storing each string in a node for a double-linked list. Problem is, I don't know how to split up a line into smaller strings, separating them where the space is.

For instance, one input is

"Duck Donald 940-666-5678"

and I'm attempting to split it into a lastname string, a firstname string, and a phnum string at the white space. The result would essentially be:

lastname==Duck
firstname==Donald
phnum==940-666-5678

How would I do this?


Solution

  • Although I not sure how you're extracting this data, I believe you should just be able to use the >> operator.

    Example:

    string lastname;
    string firstname;
    string phnum;
    ifstream myFile;
    myFile.open("example.txt");
    
    myFile >> lastname >> firstname >> phnum;