Thread: Help me again :/

  1. #1
    Registered User
    Join Date
    Oct 2005
    Location
    Brasil
    Posts
    220

    Help me again :/

    what is wrong with this?
    Code:
    string name;
                    cout<<"Voce deseja procurar os dados de qual pessoa?\nPS:para aparecer todos digite: TODOS\n";
                    cin>> name;
                    cin.ignore();
                    switch ( name ) {

  2. #2
    Registered User Dante Shamest's Avatar
    Join Date
    Apr 2003
    Posts
    970
    You can't use a switch statement on name, because it's not an integer.

    edit: changed "constant integer" to "integer"
    Last edited by Dante Shamest; 10-19-2005 at 11:06 AM.

  3. #3
    Registered User
    Join Date
    Oct 2005
    Location
    Brasil
    Posts
    220
    so what would be a integer? and how i could use switch with names?

  4. #4
    Registered User Dante Shamest's Avatar
    Join Date
    Apr 2003
    Posts
    970
    Either convert the string to an integer, or use if-else with names instead of switch.

  5. #5
    Registered User
    Join Date
    Oct 2005
    Location
    Brasil
    Posts
    220
    how do i convert the string to an integer? hehehe im sorry for your lost of time helping me :P

  6. #6
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    only strings that contain digits '0', '1', ... '9' can be converted to an integer. Strings such as "Hello World" cannot be converted. If the variable 'name' contains leading digits, then you can use either std::stringstream c++ class, or atoi(). Note: I didn't compile or test this so it might contain sytax errors.
    Code:
    std::string name = "123";
    std::streamstring str(name);
    int n;
    str >> n;
    // now n should be the integer 123

  7. #7
    Registered User Dante Shamest's Avatar
    Join Date
    Apr 2003
    Posts
    970
    Code:
    #include <iostream>  // for cin
    #include <string>    // for string
    #include <sstream>   // for stringstream
    using namespace std;
    
    int main(int argc, char *argv[])
    {
      cout << "Enter an integer: " ;
      
      // Read a line into a string.
      string line ;
      getline( cin, line );
      
      // Convert the string to an integer.
      stringstream ss( line );
      int i ;
      ss >> i ;
      
      // Conversion succeeded.
      if ( !ss )
      {
        cout << "You did not enter an integer." ; 
      } 
      
      // Conversion failed.
      else
      {
        cout << "You entered " << i << endl ;
      }
      
      cin.get();  
      return 0 ;
    }

Popular pages Recent additions subscribe to a feed