开发者

Getting user input using cin.get() in C++ question

开发者 https://www.devze.com 2023-01-02 09:58 出处:网络
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 ios

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:  " <&l开发者_StackOverflowt; 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


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.


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.


To get new line as delimiting character, you should use

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号