C++ basic string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • helraizer1
    New Member
    • Mar 2007
    • 118

    C++ basic string

    Hi folks,

    I'm very new to C++, only started learning it tonight, but I learn quite quickly (luckily).

    So far as part of a tutorial I made a basic program that asks for the users age, then returns a responce, depending on the number the user inputted. Which is pretty basic, I know.

    for this I used (c++)

    [code=C]

    #include <iostream>

    using namespace std;

    int main()
    {
    int age;

    cout<<"Please input your age: ";
    cin>> age;
    cin.ignore();

    if ( age < 13 ) {
    cout<<"You are pretty young!\n";
    }
    else if ( age == 13) {
    cout<<"Ooh, you're a teenager now!!\n";
    }
    else if ( age < 15) {
    cout<<"Still a teenager, aye?\n";
    }
    else if ( age == 16) {
    cout<<"Ooh, sweet sixteen, is it? Not so young and innocent now, are you!\n";
    }
    else if ( age < 39) {
    cout<<"Getting older now, aren't you. Go you!\n";
    }
    else if ( age == 40) {
    cout<<"Congratu lations! Life starts at 40, you know!\n";
    }
    else if ( age < 99) {
    cout<<"Getting on a bit, aren't you?\n";
    }
    else if ( age == 100 ) {
    cout<<"A whole century, wow!\n";
    }
    else {
    cout<<"Don't be silly, stop lying. You're not that old!\n";
    }
    {
    cout<<"\n\n\n\n[Please press Enter to exit]\n";
    }

    cin.get();
    }[/code]

    Which is fine, when they input an integer. but how would I adapt it (ignore the if statements) for if they were to enter a string, for a name, such as "Sam" or "James" or something? Would this be possible?

    Sam
  • RRick
    Recognized Expert Contributor
    • Feb 2007
    • 463

    #2
    cin knows about ints, doubles and strings. Just make a sting object and cin will fill it. Cin breaks on white space, so any number or letter will be converted to the string. For example:
    [code=cpp]
    std::string name;
    cout << "Please enter your first name: ";
    cin >> name;
    [/code]

    Comment

    • looker
      New Member
      • Dec 2007
      • 18

      #3
      Well, that is a good catch guy!
      Code:
      int age
      .......
      ......
      cin >> age;
      I think you know that i would cause a crash when user input char/string when prompted, because you declare age as integer, right ?
      The solution is to declare age as
      Code:
      .......................................
      .......................................
      #define MAX_INPUTS_LENGTH                (10)
      #define ERROR_INVALID_DATA               (0)
      #define ERROR_OVERLOAD_NUMBER    (1)
      #define ERROR_LESS_NUMBER             (2)
      
      //
      // you need to define more when you continue with your own code
      //
      int main()
      {
       char *ageString[MAX_INPUTS_LENGTH];
       int    age = ERROR_INVALID_DATA;
       ................................................
       ................................................
       cin >> ageString;
      
       // to be continued
      }
      Standard input is seen to be all char or string not integer.
      Then what you need to do is to analyze age just inputted and use atoi() to convert from numeric string to integer value with integer type.
      The block of code below should be the answer to your question

      Code:
       // continue from above code
       age = atoi(ageString); 
       if ( ERROR_INVALID_DATA  == age )
      {
         // return to main
         return (age);
      }
      if ( INT_MAX == age )
      {
         return (ERROR_OVERLOAD_NUMBER);
      }
       if (INT_MIN == age )
      {
         return (ERROR_LESS_NUMBER);
      }
      // You can you variable age from now on, 
      ........................................
      .............................................

      Comment

      • RRick
        Recognized Expert Contributor
        • Feb 2007
        • 463

        #4
        Looker, be careful how you combine C and C++. If you want ,you can take the input from cin and put it into a C char array. But why? cin knows about the STL string object and with the string object you don't have to worry about memory allocation and buffer overwrites. cout and cin are related in function to the C style printf and scanf. Like scanf, cin can convert the character stream to an int or double or whatever.

        Comment

        • looker
          New Member
          • Dec 2007
          • 18

          #5
          Originally posted by RRick
          Looker, be careful how you combine C and C++. If you want ,you can take the input from cin and put it into a C char array. But why? cin knows about the STL string object and with the string object you don't have to worry about memory allocation and buffer overwrites. cout and cin are related in function to the C style printf and scanf. Like scanf, cin can convert the character stream to an int or double or whatever.
          Hm.....that is a one more idea of you RRick.
          The user input is always untrusted. You can't assume that user always input integer or whatever you expected. So A good way to handle it is to assign all the input data from user into string.
          Do you think it is possible when you declare int x; then user input alpha data. It sounds so funny right ?

          Comment

          • weaknessforcats
            Recognized Expert Expert
            • Mar 2007
            • 9214

            #6
            Originally posted by looker
            So A good way to handle it is to assign all the input data from user into string.
            Do you think it is possible when you declare int x; then user input alpha data. It sounds so funny right ?
            The >> operator sets a fail bit if the user enters the wrong type of data. You can capitalize on that. Here is code ot get an integer from the user:
            [code=cpp]
            bool GetInt(int& data); //function prototype

            int main()
            {
            int test;
            bool rval;
            while (1) //infinite loop. Need CTRL+C to stop program
            {
            rval = GetInt(test);
            if (rval)
            {
            cout << "The integer is: " << test << endl;
            }
            else
            {
            cout << "Error! Eating an input character" << endl;
            //You could use cin.get() here to see what you ate
            cin.ignore();
            }

            }

            return 0;

            }

            bool GetInt(int& data)
            {
            cin >> data;
            if (cin.good())
            {
            return true;
            }
            else
            {
            cin.clear(); //clear the fail bit that got us here
            return false;
            }
            }
            [/code]

            Comment

            • joemc
              New Member
              • Dec 2007
              • 3

              #7
              I am no expert and i just signed up right now. I have made some code that does not exactly do what you want... because thats a rule here. I am breaking the no whole source code rule, but i believe this is a small program and not homework anyway.

              Before the code, just like you there are many things i still need to learn. I want to say i already know there are many better ways to do what you are looking for. most involve c++ style strings and other useful stuff. My goal to stay as simple as possible and just show you how cin.peek() works. wow, anyone else use ';' instead of '.' at end of a sentence after writing code? me grammar is awful and my spealing terrible. sorry :)

              Code:
              #include <iostream>                 
              using namespace std;
              
              int main ()
              {
                char c,name[30];                  // one character c, and one character array name
                int age;                          // one integer age;
                cout << "Enter age or name: ";    // output 
                c=cin.peek();                     // looks at first character without taken it from stream
                if ( (c >= '0') && (c <= '9') )   // c is a character so you have to check it like one
                {
                  cin>> age;                      // we are assuming becuase the first character was a numeral the rest before whitespace 
              	                                // are also numerals.  not really the greatest idea, but keeps it simple for a simple
              	                                // program.
              	cout << "Age:" << age <<"\n";   //output
                }
                else                              // if first character not a numeral
                {
                  cin >> name;                    // fill name with characters till whitespace or 30 char
              	cout << "Name:" << name <<"\n"; // Now spaces are still going to mess with you
              	                                // search google for something similiar to 
              	                                // "std string getline"
              	                                // you can get the whole line than parse for integers
                }
                return 0;                        //return 0 because we made it to the end
              }

              Comment

              Working...