?
Solved

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

Posted on 2003-12-10
6
Medium Priority
?
948 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 11

Assisted Solution

by:bcladd
bcladd earned 160 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 320 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

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…
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 goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
Suggested Courses

762 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