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
  • 35,119
  • 7
  • 92
  • 115
balaji
  • 913
  • 2
  • 11
  • 24

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
  • 246,832
  • 83
  • 321
  • 542
0

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

  cin.getline (name,256);

C++ refence for getline()

zw324
  • 25,936
  • 16
  • 82
  • 114
  • 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
  • 257
  • 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