Solved

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

Posted on 2003-12-10
6
939 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
Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

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

Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

828 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