-1

(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;
}
taylorSeries
  • 505
  • 2
  • 6
  • 18

1 Answers1

1

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.

  • 1
    If one is using cin, then they have to print their prompt and then collect whatever the user gives, right? I do not understand what you mean by separate cin and cout. – taylorSeries May 08 '22 at 06:10