CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    Mar 2004
    Posts
    216

    getline instead of cin>>

    i've got this code:

    Code:
    cout <<"insert a string: ";
    std::string s;
    cin>>s;
    when i enter a string with spaces cin only records in s til the first space.

    example:

    insert a string: Hello world!

    only hello is stored in s.

    I've heard that the getline functions solves this. I read Eckel's thinking in c++ vol 2 but i couldn't understand how to use it. Would you mind telling me?
    thanls!!

  2. #2
    Join Date
    Apr 2004
    Location
    Colchester, UK
    Posts
    97
    For example:

    Code:
    string str1;
    while(str1.empty())
    {
        cout << "Enter a string: ";
        getline(cin, str1);
        cout << endl;
    }
    Hope that helps

  3. #3
    Join Date
    Mar 2004
    Posts
    216

    Unhappy it didn't work

    I ran the debugger and after getline(cin, str1); nothing is stored in str1


  4. #4
    Join Date
    Apr 2004
    Location
    Colchester, UK
    Posts
    97
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        string str1;
        while(str1.empty())
        {
            cout << "Enter a string: ";
            getline(cin, str1);
            cout << endl;
        }
    
        cout << str1;
    
        cin.get();
        return(0);
    }
    Does that work for you? It does for me.

  5. #5
    Join Date
    Mar 2004
    Posts
    216
    thanks!! the while (str1.empty()) did it

  6. #6
    Join Date
    Apr 2004
    Posts
    14
    you can also use the gets function, which I believe is in the string.h library. What gets does is get input from STDIN until a \n is encountered.

    void main()
    {

    char buf[128];

    gets(buf);

    blah blah blah.......
    }

  7. #7
    Join Date
    Jul 2003
    Location
    Maryland
    Posts
    762
    nark, he is not using C

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured