Thread: Inputing multiple characters...

  1. #1
    C++ Master
    Join Date
    Oct 2005
    Location
    ProgramLand
    Posts
    15

    Inputing multiple characters...

    Here is my startout text RPG:

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        char charname;
        cout<<"Welcome to Tri-Dungeon RPG\n";
        cout<<"Please name your character: ";
        cin>> charname;
        cin.ignore();
        cout<<"Your character is named "<< charname <<"\n";
        cin.get();}
    But the thing is, when i input A or 3 it doesn't crash. It works. But when i enter multiple characters it crashes, how can you input multiple characters without it crashing? Thx for ur help.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    A char holds a single character. To hold multiple characters, you use a string. In C++, you #include <string> and use the string class. So instead of char, give the name variable the type string.

    BTW, that will only read in a single word. If you want to allow spaces in the name, you will have to use another function called getline, which reads the entire line input by the user including spaces.

  3. #3
    C++ Master
    Join Date
    Oct 2005
    Location
    ProgramLand
    Posts
    15
    thanks for the info.
    But for some reason getline isn't working... Do you have to add another library? If so, what is it?
    It should be:

    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        getline charname;
        cout<<"Welcome to Tri-Dungeon RPG\n";
        cout<<"Please name your character: ";
        cin>> charname;
        cin.ignore();
        cout<<"Your character is named "<< charname <<"\n";
        cin.get();}
    Last edited by Cloud_909; 02-08-2006 at 02:46 PM.

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    getline is a function, string is the type. It should be string charname.

    You don't need to use getline. If you just use string above, then it will work and you can read in one name (without spaces).

    After you get that working, if you want to read in a name with spaces, then you change cin >> charname to getline(cin, charname) because getline does input like cin >>.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 06-08-2009, 03:03 PM
  2. While loop with multiple characters
    By arctic_blizzard in forum C Programming
    Replies: 16
    Last Post: 09-20-2008, 12:25 PM
  3. HELP!!!!emergency Problem~expert please help
    By unknowppl in forum C++ Programming
    Replies: 9
    Last Post: 08-21-2008, 06:41 PM
  4. multiple characters within single quotes
    By BattlePanic in forum C Programming
    Replies: 4
    Last Post: 05-06-2008, 02:59 AM
  5. Replies: 1
    Last Post: 05-01-2003, 02:52 PM