C++ reading from a file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rippedrider50
    New Member
    • Apr 2008
    • 1

    C++ reading from a file

    Hi I would like to read from a C++ file, but the problem is the file contains ints and chars. When theres a char I need to do one thing and when there's an int I need to do another. How can I differentiate between the ints and chars when reading in from the file??
  • Studlyami
    Recognized Expert Contributor
    • Sep 2007
    • 464

    #2
    This might help you out.

    Comment

    • hsn
      New Member
      • Sep 2007
      • 237

      #3
      here is a simple way
      when you read the file char by char check if the ASCII value of the char is not in the range of numbers if it is not then save it in a char variable. if it is save it in a number.

      for example
      char c
      read in(//some file)
      c = get input
      if (ASCII of c is not in the range of numbers)
      add c to a char varible
      else
      convert c to a number and add it to an int varible

      gppd luck


      hsn

      Comment

      • oler1s
        Recognized Expert Contributor
        • Aug 2007
        • 671

        #4
        Here's what I would do. I would read the input as a string. Then attempt to convert the string to an integer. If the conversion fails, you don't have an int, so you must work with a string (which may be just a single character).

        You can Google to find out how to read input in C++ as strings (using getline). Conversion is a pretty popular question as well. You can do things the C way or the C++ way. The C++ way involves stringstreams. The C way is best done with strtol.

        Comment

        • weaknessforcats
          Recognized Expert Expert
          • Mar 2007
          • 9214

          #5
          You differentiate between chars and ints in the same file becuse you know how they were written in the first place. Otherwise, you can't tell if this byte is a char or part of an int.

          Comment

          Working...