-1

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?

Arun A S
  • 6,421
  • 4
  • 29
  • 43
  • 3
    What have you tried so far? How did (or didn't) it work? And you do know that the input operator `>>` separates input on whitespace? – Some programmer dude Feb 11 '15 at 15:17
  • No, actually, That I did not know. Been working with C++ for three years and I'm still learning things. Gimme a moment while I test it out. – Trey Brumley Feb 11 '15 at 15:26

2 Answers2

1

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;
Jamie Blue
  • 52
  • 1
  • 10
0

I am not quite sure how you are reading in from your file, but this bit of code may help you.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () 
{
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
        istringstream iss(s);
        do
        {
            string sub;
            iss >> sub;
            cout << "Substring: " << sub << endl;
        } while (iss);
    }

    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

Make sure to search Stackoverflow/Google before asking because you can find your answer really easily many times (see my resources)

Resources: http://www.cplusplus.com/doc/tutorial/files/, Split a string in C++?

MrJman006
  • 752
  • 10
  • 26