0

Please help me to solve the following program

#include<iostream>
#include<cstring>
using namespace std;
int main(){
    const int size=5;
    char name1[size], name2[size];
    cin.getline(name1, size);
    cin.getline(name2, size);
    cout<<"Name 1: "<<name1<<endl;
    cout<<"Name 2: "<<name2<<endl;
return 0;
}

When i enter more than 5 letters for name1, it skips the second cin.getline code. It directly show the cout statements. It does not get the value for name2

It want this program to take only 4 character for name1, and it should get next input for name2. How to do this, without using string?

Raj Arv
  • 1
  • 3
  • Variable Length arrays are not a part of C++. Simply declare larger C-strings. Something like 128 or 256. If you really want to control the size of the input, a loop to only grab 'n' characters is a much stronger guarantee. – sweenish Nov 24 '20 at 14:47
  • 1
    Does this answer your question? [cin.getline( ) with larger size](https://stackoverflow.com/questions/6053957/cin-getline-with-larger-size) – Joao Lima Nov 24 '20 at 14:47
  • @sweenish this code is not using variable-length arrays, since `size` is a compile-time constant, so the size of the arrays is known at compile-time. VLA sizes are only known at runtime. – Remy Lebeau Nov 24 '20 at 15:48
  • @RemyLebeau Point. I know that, just read the code wrong. If it's not all caps, I don't register constants on quick skim. – sweenish Nov 24 '20 at 16:50
  • Reduce these kinds of issues, prefer to use `std::string` instead of character arrays. – Thomas Matthews Nov 24 '20 at 18:35

0 Answers0