0

I would like to know how to get rid of the '\n' for when I execute cin.get(). For example:

#include <iostream>

int main() {
    std::cout << "How many pieces of c: ";

    struct c{
        std::string name;
        int val;
    };
    int amount;
    std::cin >> amount;
    c * c1 = new c[amount];
    std::cin.get();
    for(int i = 0; i < amount; i++){
        std::cout << "C Number " << i + 1 << ":" << std::endl;
        std::cout << "Please enter the name: ";
        c1[i].name = std::cin.get();
        std::cout << "Please enter the val: ";
        std::cin >> c1[i].val;
        std::cin.get();
    } 
    return 0;
}

I've tried using cin.get() to eliminate the '\n' thats last read after my std::cin, but my program only takes in the first name and then executes the rest of the program without letting me continue to type the rest of the name and val values. In short, I want to be able to store the rest of my name and val values. Thanks!

  • 2
    See [this](https://stackoverflow.com/questions/5838711/stdcin-input-with-spaces) and [this](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – NathanOliver Jun 27 '17 at 14:39

2 Answers2

0

For reading int, try using getline and stringstream:

std::string input(5, '\0');
int number;
std::getline(std::cin, input);
std::stringstream sstrm(input);
sstrm >> number;

For a name: You can directly use getline

std::string name(30, '\0');
std::getline(std::cin, name);
0
c1[i].name = std::cin.get();

I'm not sure why you used get() instead of operator >>, like you did two lines later. get() reads a single character - meaning, only the first character you type in is saved as name. Everything else is read (most likely unsuccessfully) into val, and then new line character is, just like you intended, digested by the final get().

Pontifex
  • 136
  • 6