Thread: using cin.geline() with a string (not a char array)

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    106

    using cin.geline() with a string (not a char array)

    ok, the answer to this is probably simple, but i haven't done it in a while...

    the following works...
    Code:
    ...
    
    int main() {
         char name[10]={'\0'};
         
         cin.getline(name,10);
    }
    but the following, for some reason, won't
    Code:
    ...
    #include <string>
    using namespace std;
    
    int main() {
         string name;
    
         cin.getline(name,10);
    }
    could anyone explain why? thanks in advance. borland 5.02
    Last edited by agerealm; 09-12-2002 at 10:47 AM.

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Syntax
    istream& getline(char*, int, char = '\n');
    istream& getline(signed char*, int, char = '\n');
    istream& getline(unsigned char*, int, char = '\n');

    Description
    The getline member function extracts up to the delimiter, puts the characters in the buffer, removes the delimiter from the input stream and does not put the delimiter into the buffer.
    You have to use a char* as parameter, not a string object. That's the problem.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    106
    cool.thanks man

  4. #4
    ¡Amo fútbol!
    Join Date
    Dec 2001
    Posts
    2,138
    char buffer[10];
    string name;
    cin.getline(buffer, 9, '\n');
    name=buffer;

  5. #5
    Registered User
    Join Date
    Nov 2001
    Posts
    1,348
    Here is an example of the use of a string object with cin.

    Code:
    string dbText;
    
    std::getline(cin, dbText);
    // dbText holds characters up to carriage return.
    Kuphryn

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  2. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  3. Character arrays
    By PsychoBrat in forum C++ Programming
    Replies: 7
    Last Post: 06-21-2002, 12:02 PM
  4. Strings are V important...
    By NANO in forum C++ Programming
    Replies: 15
    Last Post: 04-14-2002, 11:57 AM
  5. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM