Scanning input of different types

This is a discussion on Scanning input of different types within the C Programming forums, part of the General Programming Boards category; Ok, I am writing a program to read a line of input by the user/from a datafile, and manipulating this ...

  1. #1
    Registered User
    Join Date
    Apr 2012
    Posts
    1

    Scanning input of different types

    Ok, I am writing a program to read a line of input by the user/from a datafile, and manipulating this data using the ADT stacks. Im having an issue. I have to read in a line of input similar to the following.

    7 3 12 * % 3 13 / + 6 - 17 + p

    Each integer it reads, it has to place it in the stack, but if it reads a operator, then it performs that with the top 2 number on the stack (ex. when it reads * in the line above, it will multiply 12 and 3.

    The problem im having is, how can i make c know if what it is reading is an integer or a character. I tried this with just integers, using scanf and %d as the placeholder. It worked fine, and placed the number in the stack. But as soon as i entered the operators in the line, it gives me a segmentation fault. As of right now, its just scanning everything as a integer, but obviously if there is a + sign, that is not an integer. Any idea how i could read a whole line of data input with integers and characters?

    I wish i could just do:

    Code:
    if ( input = integer)
        place in stack;     //pseudocode
    else
    {
        if (input = '+');
        {
            perform addition;
        }
        else if (input = '-' );  
        {
            perform subtraction;
        }
    etc, etc. But i dont know how to do this, and i would still be lost on what placeholder to use when scanfing. Any help would be appreciated.

    Thanks
    Alex

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    You need to read them as strings, with scanf (or fscanf) and %s. Then test the first character to see if it's a digit. If it is, use atoi() to turn it into an integer.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Scanning input data
    By papermate in forum C Programming
    Replies: 38
    Last Post: 04-25-2010, 02:56 AM
  2. Accepting Multiple Types of Input
    By Junior89 in forum C++ Programming
    Replies: 2
    Last Post: 03-07-2006, 11:25 PM
  3. Improper Scanning of Redirected Input
    By alexpos in forum C Programming
    Replies: 7
    Last Post: 10-21-2005, 02:21 PM
  4. Differentiating Between Different Input Types
    By lexxonnet in forum C++ Programming
    Replies: 6
    Last Post: 07-27-2003, 03:20 AM
  5. reading input files with different types of data
    By sanu in forum C++ Programming
    Replies: 4
    Last Post: 06-27-2002, 09:15 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21