Thread: Reading a string

  1. #1
    Registered User
    Join Date
    Oct 2001

    Question Reading a string

    I am writing a stack program to evaluate infix expressions and I have everything done and ready to go except one hurdle I cannot seem to pass. Let's say I have a string test; now I read in 4 + 3 5 6 - * into the string. How do i operate on the string character by character so that each character can have an operation performed on it (and yes it has to have spaces between each char/int). I know it's probably an easy answer but I'm stumped. Thanks ya'll!

  2. #2
    Registered User *pointer's Avatar
    Join Date
    Oct 2001
    Parse the string into individual variables and perform your operations. A string is just a char array, so you can do something like this
    for ( int i = 0; i < SIZE; i++ ) {
        if ( isnumeric( string[i] ) ) {
            num[i] = string[i];
        else if ( isalpha( string[i] ) ) {
            if ( string[i] == '+' || string[i] == '-' || string[i] == '*' || string[i] == '/' ) {
                oper[i] = string[i];
            else {
                cout << "Error, invalid operator" << endl;
        else {
            cout << "Invalid input" << endl;
    pointer = NULL

  3. #3
    Registered User
    Join Date
    Aug 2001
    *pointers way to parse should work for integer input but it won't work for decimal input and it has trouble with parenthesis (if you are tuly using an infix expression). A more general way to parse would be to use strtok() or equivalent string class member function using space a the delimiter, assuming there is a space between each parenthesis, operand, and operator. If spaces aren't appropriately supplied, they can be put there before the parsing, but it is easier to request input to be space delimited

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Please check my C++
    By csonx_p in forum C++ Programming
    Replies: 263
    Last Post: 07-24-2008, 09:20 AM
  2. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  3. IRC, reading the stream
    By Iyouboushi in forum C# Programming
    Replies: 6
    Last Post: 08-03-2006, 05:34 PM
  4. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  5. problems with overloaded '+' again
    By Brain Cell in forum C++ Programming
    Replies: 9
    Last Post: 04-14-2005, 05:13 PM