0

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--

  • Can you clarify your understanding of how this specific `get()` overload work, step by step? In order for the shown code to work each `get()` must obviously read an entire line of text, including the trailing newline, but somehow truncate each line and copy the leading two characters into the array, followed by a `\0`. What, exactly, in your C++ textbook's description of this `get()` overload led you to believe that this is how it works? – Sam Varshavchik Aug 30 '22 at 00:46
  • You also need to describe what input you are providing. Presumably (you haven't mentioned it) you are hitting the key after the first two letters. The first call of `cin.get()` will stop when it encounters the `'\n'` in the stream AND leave that `'\n'` in the stream buffer. The second call will encounter that `'\n'` and return immediately, and leave that `'\n'` in the stream ..... You could find this by reading the documentation e.g. https://en.cppreference.com/w/cpp/io/basic_istream/get – Peter Aug 30 '22 at 00:47
  • When reading the above documentation link, pay special attention to points 3) and 4) – user4581301 Aug 30 '22 at 00:49
  • The way you are using `cin.get()` will not allow you to reach your goal the way you want. Don't use `char[]`, use `std::string` instead with `cin >>` or `std::getline()`, and then you can use `std::string::substr()` to extract the first 2 chars of each input. – Remy Lebeau Aug 30 '22 at 00:49

1 Answers1

0

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--
273K
  • 29,503
  • 10
  • 41
  • 64