Thread: best way to prevent missreads

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    222

    best way to prevent missreads

    hi,

    what would be the best (and jet simplest) way to avoid errors in the following situation.


    so i am reading a two column file:

    Code:
    fstream fs;
    int a, b;
    
    while(fs.good()){
      fs >> a >> b;
    }
    file

    Code:
    1 2
    2 3
    4 6
    6 
    7 8
    2 7 8 
       6
    ...
    if values are missin, or not formated properly, the above read function will produce problems. what would be the most effective way to limit the read to 2 columns only and if no value is assigned then set the value to -1.


    thnx

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Read the entire line into a string then process that string with a stringstream. If the string only contains one item the stream will be in an error state and you can discard/edit any input. If you can't just discard any "extra" information you'll need to "loop" through the string to insure there are only two entries.

    Jim

  3. #3
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by baxy View Post
    if values are missin, or not formated properly, the above read function will produce problems. what would be the most effective way to limit the read to 2 columns only and if no value is assigned then set the value to -1.
    Just declare two more variables, read into those, then check fs.good(). If fs.good(), then store those variables into a and b, otherwise store -1 into a and b.

    If you want something more advanced, like the ability to keep parsing after receiving a line with an error on it, then you'll need to do something more complicated, like read a line at a time into a stringstream then parse it out of that.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. prevent duplicate age when insert age
    By TheSniper102 in forum C Programming
    Replies: 3
    Last Post: 10-17-2014, 05:04 PM
  2. how to prevent encapsulation in c++ ?
    By mannu1200 in forum C++ Programming
    Replies: 11
    Last Post: 01-26-2014, 02:17 AM
  3. Prevent to type zero as the first digit in value
    By cecylia in forum C Programming
    Replies: 4
    Last Post: 04-04-2013, 09:35 PM
  4. prevent piping?
    By barneygumble742 in forum C++ Programming
    Replies: 2
    Last Post: 12-29-2005, 01:07 AM
  5. prevent exiting
    By Unregistered in forum A Brief History of Cprogramming.com
    Replies: 4
    Last Post: 12-12-2001, 02:57 PM