newbie question: Char string cutting


#1

Hello,

  I've a little problem with a code routine here.
  I'm opening a file using std::ifstream::open, with standard opening attributes std::ios::in
  
  now I read the complete file with std::ifstream::read( ... )
  and put the content into a char buffer:
 
      std::ifstream _fileInputStream;
      _fileInputStream.open( "File.txt", std::ios::in );
      
      char buffer[ 500 ];
      _fileInputStream.read( buffer, sizeof( buffer ) );
      
  with that the buffer is full with the data from the file.
  
  But now:
  The data structure looks like this:

      X-Coords	Y-Coords
      23		112
      25		134
      34		188
      .			 
      .			 
      .			 
      

And I have to move the int values into a


   struct d_Struct
   {
   	  int x, y;
   }
   

But how can I cut the char string buffer into its x and y parts ??

Thanks for all help,
ciao,
lex


#2

I would suggest converting it to an std::string, and then using the functions inherrent to strings…

This page: http://www.cppreference.com/cppstring.html is a good reference page…

Especially look at the functions find_first_of(), find_first_not_of() and substr()

If I were doing this, I’d probably write a generic tokenizer (actually, I lie… if I were doing this, I’d use the generic tokenizer that I wrote ages ago) that you could pass that line to and get a vector of strings back…


#3

Hugh’s right, you should try whenever possible to work at the highest level, employ a tokenizer. Then you’ll need to use atoi (or some other API to turn “42” into 42). I think you’d win big by taking a look at the Boost C++ library (www.boost.org). If it’s tokenizers you want have a look-see at http://www.boost.org/libs/tokenizer/index.html.


#4

well since those are integers, just use strstreams.


#include<iostream>
#inlcude<string>
#include<fstream>
#include<sstream>
using namespace std;
 
int main()
{
 ifstream file("textfile.txt");
 stringstream stream;
 stream << file.rdbuf();
 
 // read x
 int x = 0;
 stream >> x;
 cout << "x = " << x << endl;
 
 // ready y
 int y = 0;
 stream >> y;
 cout << "y = " << y << endl;
 
 // repeat
 
 return 0;
}


#5

This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.