Hello! The text file is separated by tabs..I have used a struc as below:

struct scores
      {	int maths
	    int phy;
	    int bio;
	    int chem;
	    int eng;
	    int total;
     struct class
     {	int class_id;
        char name[50];

       ifstream fin;
        char buf[100];
        string a;
        char delims[] = "\t";
        for(int i=0; i<a.size(); i++)
         buf[i] = a[i];         
        char *result = NULL;
        result = strtok( buf, delims );
        while( result != NULL ) {
       printf( "result is \"%s\"\n", result );
       result = strtok( NULL, delims );

when i compile i get: (I have just read one line of the text file)

result is 67
result is 34
result is 34
result is 90
result is 67
result is 76
result is 2
result is Science_G

Now i need to store each column(eng marks,phy marks,..) in an array
as i need to sort them later..
I think i have to use getnexttoken..
can someone guide me how to do it?

8 Years
Discussion Span
Last Post by Lerner

You can use stringstreams:

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

int main()

  std::string tmp = "hi\tthis\tis\ta\ttest"; 
  std::vector <std::string> array;
  std::string token;
  std::istringstream iss ( tmp );

  while ( getline ( iss, token, '\t' ) )
    array.push_back ( token );

  //show tokens
  std::cout << array[0] << std::endl;
  std::cout << array[1];



Or if you are more comfortable with c style syntax



I dont know how to use that..:(

do you know how to use the Getnexttoken?

for (i = 0; i < ntokens; i++) 


i think this line stores the tokens in an array rite>


First of all decide whether you are going to use C or C++. The ifstream object and std::string object suggest you are using C++. However, the prinf() for such a simple object suggests you are using C. It's important because the word class is a keyword in C++ and shouldn't be used as the name of a user defined type as you do if this is C++, though it may work in C, whereas ifstreams and std::string won't work in C.

Assuming you are trying to use C++ then I'd use the >> operator and (if any variable could have embedded white space) getline() instead of strtok() to parse the input into the various variables. How you store the variables to sort them at a later time, output the sorted values, etc, is up to you. Perhaps you could put all the variables in a single struct and then you could sort the structs based on whichever member variable you wanted.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.