-1

My text file is like:

mr,John Abrahm,USA,30,M
Mr,Harry,UK,40,M
Mr,Jack,USA,50,M

I want to do like:

title=mr  
name=John Abrahm  
country=USA  
age=30  
gender=M

So far my code is like:

ifstream inputFile("text.txt");
string line;
while (getline(inputFile, line))
{
    istringstream ss(line);

    string title;
    string name;
    string country;
    char gender;

    ss >> title>>nam>>age>>country>>gender;
    cout <<gender<< endl;
}
Azeem
  • 11,148
  • 4
  • 27
  • 40
aatanka
  • 31
  • 3
  • 2
    Welcome to stackoverflow.com. Please take some time to read [the help pages](http://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also please [take the tour](http://stackoverflow.com/tour) and [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). Lastly please learn how to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). – Some programmer dude Aug 22 '17 at 10:34

1 Answers1

0

You might be looking for strtok.

A sample code:

#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="mr,John Abrahm,USA,30,M";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,");
  while (pch != NULL)
 {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,");
 }
 return 0;
}

Returns:

Splitting string mr,JOhn Abrahm,USA,30,M into tokens:

mr

John Abrahm

USA

30

M

Instead of printing the strings you could assign them to variables. You might wanna look at this answer.

EDIT : For several rows, say you wanna extract all the 5 entries in each row in 5 different arrays. You first do something like:

pch1 = strtok (str," \n");

This gives you one particular row which you can further divide with

pch = strtok (pch1," ,");

This would obviously be possible only with a nested loop.

Vivek Shankar
  • 770
  • 1
  • 15
  • 37
  • Thank you for the suggestion. But, i am using c++ and my file contains many rows (say 100). – aatanka Aug 22 '17 at 11:06
  • @aatanka I don't see why that's a problem. `strtok` is available in c++. You only require basic manipulation to extend my answer for several rows. Please see my edit. – Vivek Shankar Aug 22 '17 at 13:39