6

I have to read a whole line from the console and store it into a std::string and a char array, e.g.

"Hi this is balaji"

Now I have to read the above string and store it into string. I tried it using the getline() function.

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
balaji
  • 1,075
  • 3
  • 12
  • 26

3 Answers3

17

Try:

#include <string>
#include <iostream>

int main()
{
    std::string line;

    std::getline(std::cin, line);  // read a line from std::cin into line

    std::cout << "Your Line Was (" << line << ")\n";

    std::getline(std::cin, line);  // Waits for the user to hit enter before closing the program
}
Martin York
  • 257,169
  • 86
  • 333
  • 562
0

Maybe there's something wrong with how you use cin.getline()?

  cin.getline (name,256);

C++ refence for getline()

zw324
  • 26,764
  • 16
  • 85
  • 118
  • 2
    Don't use that version of getline. What happens if the line is bigger than 256 characters or even worse what if the buffer is smaller than 256 characters. – Martin York Apr 22 '11 at 21:00
0

Maybe

string a;
cin >> a;

cout << a << endl;

Or something like that?

nagymafla
  • 267
  • 5
  • 10
  • 2
    it reads some input from the user, but the OP specifically asked for help with reading a "whole line", and this doesn't. – Jerry Coffin Apr 22 '11 at 21:05