是否有一种使用方法(std :: cin).get()在要求输入时接受新线?

发布于 2025-01-27 05:32:10 字数 1125 浏览 1 评论 0原文

(std :: cin).get()

我想使用std :: cin收集带有空间的弦,例如“花1/2盎司”。当我添加一个空间然后按Enter IT退出程序时,而不是收集其余的输入。 找到此 stdcin-and-why-a-a-a-newline-remains 我看到了评论说您可以使用.get(),但它对我不起作用。

如何使用(std :: cin).get()输入数据时接受空间?

#include <iostream>
#include <vector>
#include <fstream> // std::filebuf

using std::cout, std::cin, std::string, std::endl;

int main(int argc, char const *argv[])
{
    
    string total, quantity, dealer;
    cout << "Total($): " << endl; (cin >> total).get();
     // If there's a space in total, it doesn't collect the other
     // variables
    cout << "Quantity: " << endl; cin >> quantity;
    cout << "dealer: " << endl; cin >> dealer;
    
    std::filebuf fb;
    fb.open ("file.txt",std::ios::out);
    std::ostream os(&fb);
    os << total << endl << quantity << endl << dealer << endl;
    fb.close();


    return 0;
}

(std::cin).get()

I want to use std::cin to collect a string with spaces, like "1/2 oz of flower". When I add a space and then press enter it exits the program instead of collecting the rest of the input.
Found this stdcin-and-why-a-newline-remains and I saw a comment that says you can use .get(), but its not working for me.

How to use (std::cin).get() to accept the spaces when inputing data?

#include <iostream>
#include <vector>
#include <fstream> // std::filebuf

using std::cout, std::cin, std::string, std::endl;

int main(int argc, char const *argv[])
{
    
    string total, quantity, dealer;
    cout << "Total($): " << endl; (cin >> total).get();
     // If there's a space in total, it doesn't collect the other
     // variables
    cout << "Quantity: " << endl; cin >> quantity;
    cout << "dealer: " << endl; cin >> dealer;
    
    std::filebuf fb;
    fb.open ("file.txt",std::ios::out);
    std::ostream os(&fb);
    os << total << endl << quantity << endl << dealer << endl;
    fb.close();


    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

痕至 2025-02-03 05:32:10

我认为您应该使用 https://en.cppreference.com/w/cpp /string/basic_string/getline 解析整个输入,然后根据您的需求将其分配在空间上。

I think you should use https://en.cppreference.com/w/cpp/string/basic_string/getline to parse the whole input and then split it on space according to your needs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文