Home > Net >  Doesn't let me input new data via cin.get after the first one
Doesn't let me input new data via cin.get after the first one

Time:08-30

I tried to make a code that takes the first two letters in three separate arrays, and concatenate them. For example, I put Dog, Cat, Rabbit, and it must show "DoCaRa". I tried to use cin.get but it only reads the first one, then it doesn´t let me enter new arrays. Here's the code:

#include <iostream>
#include <string.h> 
using namespace std;

int main()
{
 char or1[99],or2[99],or3[99];
 cout << "Enter array: ";
 cin.get (or1, 3);
 cout << "Enter array: ";
 cin.get (or2, 3);
 cout << "Enter array: ";
 cin.get (or3, 3);
 cout << "\n--" << or1 << or2 << or3 << "--\n";
} 

Output: Enter array: dog Enter array: Enter array: --dog--

CodePudding user response:

It would be better to use gets() function. This function gets entire characters including whitespaces in the row from command.

CodePudding user response:

cin.get (or1, 3); reads at most 2 chars until line end but leaves other characters and end-of-line character in the stream, so cin.get (or1, 3); reads do, cin.get (or2, 3); reads g until line end, cin.get (or3, 3); meets line end and will not give new inputs. Use the entire buffers for reading and cin.get() to consume end-of-line character.

#include <iostream>
#include <string> 
using namespace std;

int main()
{
 char or1[99],or2[99],or3[99];
 cout << "Enter array: ";
 cin.get (or1, 99); cin.get(); or1[2] = 0;
 cout << "Enter array: ";
 cin.get (or2, 99); cin.get(); or2[2] = 0;
 cout << "Enter array: ";
 cin.get (or3, 99); cin.get(); or3[2] = 0;
 cout << "\n--" << or1 << or2 << or3 << "--\n";
}
// Output:
// --DoCaRa--
  • Related