35

I'm trying to store the input that user enters through console. so I need to include the "enter" and any white space.

But cin stops giving me input after the first space.

Is there a way to read whole lines until CTRL+Z is pressed, or something?

unwind
  • 391,730
  • 64
  • 469
  • 606
Katia
  • 679
  • 2
  • 15
  • 42
  • Possible duplicate. Please look at http://stackoverflow.com/questions/2765462/how-to-cin-space-in-c – mkaes May 04 '11 at 11:52
  • I didn't find this post while searching . if I did, I would post another one ^^ sorry , I'll try looking deeper next time – Katia May 04 '11 at 12:03

5 Answers5

56

is there a way like readLines till CTRL+Z is pressed or something ??

Yes, precisely like this, using the free std::getline function (not the istream method of the same name!):

string line;

while (getline(cin, line)) {
    // do something with the line
}

This will read lines (including whitespace, but without ending newline) from the input until either the end of input is reached or cin signals an error.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 1
    @katia Only `getline` reads the whole line. If you input a string via `cin >> line` then it reads only until the first whitespace. – Konrad Rudolph May 04 '11 at 11:58
6
#include <iostream>
#include <string>
using namespace std;

int main() 
    string s;
    while( getline( cin, s ) ) {
       // do something with s
    }
}
1

For my program, I wrote the following bit of code that reads every single character of input until ctrl+x is pressed. Here's the code:

char a;
string b;
while (a != 24)
{
cin.get(a);
b=b+a;
}
cout << b;

For Ctrl+z, enter this:

char a;
string b;
while (a != 26)
{
cin.get(a);
b=b+a;
}
cout << b;

I can't confirm that the ctr+z solution works, as I'm on a UNIX machine, and ctrl+z kills the program. It may or may not work for windows, however; You'd have to see for yourself.

Jonny
  • 11
  • 1
0
#include <string>
#include <iostream>

int main()
{

    std::cout << "enter your name: ";

    std::string name;

    std::getline(std::cin, name);

    return 0;

}
The_Outsider
  • 1,875
  • 2
  • 24
  • 42
  • 2
    Welcome to Stack Overflow! Though we thank you for your answer, it would be better if it provided additional value on top of the other answers. In this case, your answer does not provide additional value, since another user already posted that solution. If a previous answer was helpful to you, you should vote it up instead of repeating the same information. – Toby Speight Aug 01 '17 at 16:54
-2

You can use the getline function in c++

#include<iostream>
using namespace std;
int main()
{
    char msg[100];
    cin.getline(msg,100);
    return 0;
}