Thread: Destinguish between numbers and words

  1. #1
    Registered User
    Join Date
    Sep 2006
    Location
    Kansas City
    Posts
    76

    Destinguish between numbers and words

    I have a text file with numbers and words, and I want to read only the numbers (double)and place then into a vector.

    How can I do this?

    So far I have

    Code:
    double x;
        while (input >> x) // put input from file into vector
       {
              if (!(input >> x))
              {
                   cout << "error - word" << endl;
              }
              else
                  input_vec.push_back (x);   
      }

  2. #2
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    stringstreams are always a good option:

    Code:
    #include <fstream>
    #include <sstream>
    #include <string>
    #include <vector>
    
    int main( void ) {
      std::ifstream in( "test.txt" );
    
      if ( !in ) 
        return 1;
    
      double number;
      std::string str;
      std::vector<double> vd;
    
      while ( in >> str ) {
        std::stringstream ss(str);
    
        if ( ss >> number )
          vd.push_back( number );
      }
    
      in.close();
    
      return 0;
    }
    Probably bugs in there ... didn't compile it.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >How can I do this?
    Probably something like this:
    Code:
    std::string word;
    double x;
    
    for ( ; ; ) {
      if ( !( std::cin>> x ) ) {
        // Try to skip a word
        if ( !( std::cin>> word ) ) {
          // Input error
          break;
        }
      }
      else
        input_vec.push_back ( x );
    }
    My best code is written with the delete key.

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Make sure to call input.clear() if the read fails and you are re-using the stream, otherwise all the subsequent reads will fail.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 12-21-2007, 01:38 PM
  2. Numbers In Words
    By year2038bug in forum C Programming
    Replies: 2
    Last Post: 09-08-2005, 10:21 AM
  3. Read words and numbers from a file
    By atari400 in forum C Programming
    Replies: 5
    Last Post: 11-04-2004, 04:55 PM
  4. converting numbers to words
    By Zim in forum C Programming
    Replies: 16
    Last Post: 05-07-2003, 05:42 AM
  5. the definition of a mathematical "average" or "mean"
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 7
    Last Post: 12-03-2002, 11:15 AM