Solved

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

Posted on 2003-12-10
6
937 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
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++.

895 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

13 Experts available now in Live!

Get 1:1 Help Now