I'm trying to use a getline function in my program. I have the correct cout function but when I try and enter my input the program keeps wanting me to enter a couple of times and then that's what comes out. I'm very confused on what I'm doing wrong in my program. This is what I have.

#include <iostream>
#include <cstring>

int main()
{
    using namespace std;

    string str2;
    cout<<"Enter a line of input for str2: ";
    getline (cin, str2);
    cin>>str2;
    cout<<"Contents of str2: ";
    cout<<str2<<endl;


    return 0;
}

Made a few changes to it and it works fine. Read the comments.

#include <iostream>
#include <string> //use string not cstring
using namespace std; //move using namespace std; up here

int main()
{
    string str2;
    cout<<"Enter a line of input for str2: ";
    getline (cin, str2);
    //remove cin >> str2;
    cout<<"Contents of str2: ";
    cout<<str2<<endl;

    return 0;
}

I'm trying to use a getline function in my program. I have the correct cout function but when I try and enter my input the program keeps wanting me to enter a couple of times and then that's what comes out. I'm very confused on what I'm doing wrong in my program. This is what I have.

#include <iostream>
#include <cstring>

int main()
{
    using namespace std;

    string str2;
    cout<<"Enter a line of input for str2: ";
    getline (cin, str2);
    cin>>str2;
    cout<<"Contents of str2: ";
    cout<<str2<<endl;


    return 0;
}

The statement getline (cin, str2); IS your input statement. You do not need the next statement " cin>>str2; ". It is redundant.

I have one more question. After writing the rest of the program I need to copy the contents of cstr1 to str1 and print the new contents of str1. Then the contents of str2 to cstr1. I'm not quite sure how to do this. Here is my program.

#include <iostream>
#include <cstring>

int main()
{
    using namespace std;

    string str2;
    cout<<"Enter a line of input for str2: ";
    getline (cin, str2);
    cout<<"Contents of str2: ";
    cout<<str2<<endl;

    string str1[4];
    cout<<"Enter a line of input for str1: ";
    cin.getline (str1, 4);
    cout<<"Contents of str1: ";
    cout<<str1<<endl;

    string s1, s2 = "Hello", s3 = "Good", s4 = "Morning";
    s1 = s2;
    s1 = s3;
    s1 = s4;
    s2 [0] = 'X';
    s4 [6] = 'X';
    cout<<"Contents of str2 after string processing: ";
    cout<<" "<<s2<<s3<<s4<<endl;

    char cstr1 [] = "All The Best";
    cout<<cstr1;
    string str1;
    str1 = cstr1;

    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.