1

note: this is in C++ but using C-style strings

hello SO,

I'm working on an assignment and I need to get input from the console and save it to a cstring. Everything compiles fine, but when the program runs, it just skips over getting input from the user. So it will output: "Enter string to be inserted: " then skip the cin.getline function, then execute the next command.

Here's my header files, the declaration of the cstring, and the line of code I'm having trouble with.

#include "stdafx.h"
#include <iostream>
#include <cstring>

using namespace std;

int main()
{
  char tempCString[500] = {};

//...code snipit...

  cout << "Enter string to be inserted: " << endl;
  cin.getline(tempCString, 500, '\n'); //I've also tried cin.getline(tempCString, 500);

//...end code snipit...

  return 0;
}

note: I can't use "cin >> tempCString" becaues it will only get the input up to the first space, I need to get input from the console of everything up to the newline.

Thank you

Community
  • 1
  • 1
Logan Besecker
  • 2,733
  • 4
  • 23
  • 21

1 Answers1

2

Try clearing cin's buffer before getting new input:

#include <limits>

cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max());
cout << "Enter string to be inserted: " << endl;
cin.getline(tempCString, sizeof(tempCString), '\n');

See How do I flush the cin buffer?

Community
  • 1
  • 1
Emile Cormier
  • 28,391
  • 15
  • 94
  • 122