简体   繁体   English

在C ++问题中使用cin.get()获取用户输入

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

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. 我包括iostream,此代码段位于我的主要功能中。

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. 似乎只是打印出两个cout语句,然后结束。 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. 我的建议是忘记该代码段的存在,而是查找std::getline 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. 当然,您可以像std::cin >> buffer一样使用流提取,但是这样做只会读取输入的一个“单词”,而不是您之前的代码试图读取的整个行。

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. 只是要检查在文件中键入一些数据,然后运行程序并添加“ <myfile”以查看数据是否已加载到缓冲区中。

You need to do some console manipulation if you want to wait for data. 如果要等待数据,则需要进行一些控制台操作。

要获得新行作为分隔符,您应该使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM