0

I'm not sure what I'm missing here. This is a snippet of code that I found on a site and I placed it in my program to see how it works and then I would modify it to my liking later. I am including iostream and this code snippet is in my main function.

char buffer[80];
cout << "Enter the string: ";
cin.get(buffer, 79);       // get up to 79 or newline
cout << "Here's the buffer:  " << buffer << endl;

What is happening is that the program never asks for the user input. It just seems to print out the two cout statements and then ends. The site where I got the snippet from shows the output of:

Enter the string: Hello World
Here's the buffer: Hello World
4
  • 1
    Shouldn't it be cout << "Enter the string: " << endl; ? Commented Jun 7, 2010 at 20:49
  • 1
    why? It shouldn't matter Commented Jun 7, 2010 at 20:52
  • That depends entirely on your UI design. If you want the string entered on the same line as the prompt, then no, it shouldn't. Commented Jun 7, 2010 at 20:54
  • Bo is correct, adding << endl does not affect the overall issue. It just formats things differently. Commented Jun 7, 2010 at 20:55

3 Answers 3

1

My advice would be to forget the existence of this snippet and look up std::getline instead. You'd use it something like this:

#include <string>
#include <iostream>

int main() {
    std::string buffer;

    std::getline(buffer, std::cin);
    std::cout << "Here's the buffer: " << buffer;
    return 0;
}

You can, of course, use stream extraction like std::cin >> buffer, but doing so will read only a single "word" of input, not a whole line like your previous code tried to do.

Sign up to request clarification or add additional context in comments.

Comments

1

The code returns whatever was in the input buffer at the time, most likely nothing.

Just to check type some data in a file, then run your program and add "< myfile" to see if the data gets loaded in your buffer.

You need to do some console manipulation if you want to wait for data.

2 Comments

Plus 1 for actually trying to answer the question rather than telling the OP "don't do that, do something else!" You're actually trying to answer the question he's asking, which is great IMO, because this is something different than EVERY OTHER POSTER is advocating. The OP is trying to take AT MAXIMUM a certain number of characters, which no answer (as of this comment) is helping with except yours.
Thanks Florin. Based on your post I think I figured out what I was looking to do. All I had to do was add in a cin.get() before the line with cin.get(buffer, 79); and that seems to display everything.
0

To get new line as delimiting character, you should use

cin.get(buffer, 79, '\n');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.