Solved

C++ : Read a string, and break words by space ....

Posted on 2003-12-10
6
936 Views
Last Modified: 2012-08-14

 Hi C++ Experts,

     I  want  to write a code, which read the first line of a file, and then determine how many columns are there in the first line (so will be in the file). The columns are separated by space. I wrote the following code, but it is kind of ugly and I don't like it ....... I am wondering if anyone could please suggest  some more elegant ways of doing this ? (Perhaps need to incorporate some script ?) I want all in one program, since I would need to declare something later in the code based on the number of columns in the file.

--------------------------------------------------------------------------
#include <fstream>
#include <iostream>
#include <string>

int main()
{
    ifstream input("Person.txt") ;
    ofstream output("temp_file.txt") ;
    string temp ;
    getline(input, temp) ;
    output << temp ;
    output.close() ;

    ifstream input1("temp_file.txt") ;
    cout << "the columns of the file are: " << endl ;
    while(input1){
     string temp1 ;
     input1 >> temp1 ;
     cout << temp1 << endl ;
    }
 
    system("rm temp_file.txt") ;

    return 0 ;
}
------------------------------
and the Person.txt looks like :

Name     Age     Height    Weight    Eye_colors
John     11      5'2"       100lbs    brown
Mary     15      6'         150lbs    green
Dave     12      5'5"       140lbs    blue
0
Comment
Question by:meow00
  • 3
  • 2
6 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 9912719
You could either use 'strtok()'

/* STRTOK.C: In this program, a loop uses strtok
 * to print all the tokens (separated by commas
 * or blanks) in the string named "string".
 */

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

char string[] = "A string\tof ,,tokens\nand some  more tokens";
char seps[]   = " ,\t\n";
char *token;

void main( void )
{
   printf( "%s\n\nTokens:\n", string );
   /* Establish string and get the first token: */
   token = strtok( string, seps );
   while( token != NULL )
   {
      /* While there are tokens in "string" */
      printf( " %s\n", token );
      /* Get next token: */
      token = strtok( NULL, seps );
   }
}

or

http://www.boost.org/libs/tokenizer/tokenizer.htm

0
 
LVL 11

Expert Comment

by:bcladd
ID: 9912755
_Accelerated C++_ by Koenig and Moo has a good exmaple of a string splitter, too. Even without the book you can get their source code at http://www.acceleratedcpp.com/. It takes a string and splits it into a vector of strings, one entry per "word" for some definition of word (non-space between spaces).

I would suggest the book, too, since it is a good read.

-bcl
0
 
LVL 1

Author Comment

by:meow00
ID: 9913010
Hello,

   Thanks for the answers.... I just have one more question about jkr's answer. What if I have a string "string" as follows :
--------------------------------
#include <string>
#include <cstdio>
#include <iostream>
#include <fstream>

char seps[]   = " ,.!a\t\n";
char *token;
string meow = "I am the laziest cat in the world...meow " ;
char woof[] = " I am,a happy dog !" ;

void main( void )
{
//   token = strtok(meow.c_str(), seps) ;  //...line01
   token = strtok(woof,seps) ;
   while(token != NULL){
    cout << token << endl ;
    token = strtok(NULL, seps) ;
   }
}
---------------------------------------------
 line01 doesn't work now ......
 Is there anyway to make line01 work ? thanks !

 meow ......
~
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 11

Assisted Solution

by:bcladd
bcladd earned 40 total points
ID: 9913086
You need to copy the contents of the string into an array of char because strtok is brutally destructive to the character string tokenized.

Try something like

char * meowCh = new char[meow.length() + 1];
strcpy(meowCh, meow.c_str());

and then tokenize meowCh and delete[] when you're done.

-bcl
0
 
LVL 86

Accepted Solution

by:
jkr earned 80 total points
ID: 9913124
>>is brutally destructive to the character string tokenized

Yup - I'd use

  char* woof = strdup(meow.c_str()) ;
  token = strtok(woof,seps) ;

// ...

  free(woof);

though...
0
 
LVL 11

Expert Comment

by:bcladd
ID: 9913153
Sure, show an easier way to accomplish the same thing.

<smile>

-bcl
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now