String Input Problem :(

I am trying to enter the length of a string and then the string. However the string is not taking the input. Plz reply fast, thanks in advance :)

#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
int main()
{
int n;
cout<<"Enter The Length: ";
cin>>n;
string s;
getline(cin,s);
cout<<s;
getch();
return 0;
}
The reason is that when you have done cin >> n, a newline is left over that the getline takes. You need to ignore it, like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <limits>
//...

int main() {
    int n;
    std::cout << "Enter the length: ";
    std::cin >> n;
    // Ignore every character up to the newline
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    std::string s;
    std::getline(std::cin, s);
    std::cout << s;

    // Alternate method of pausing the console that doesn't require conio.h
    std::cin.sync();
    std::cin.get();

    return 0;
}
Topic archived. No new replies allowed.