0

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std ;
struct st
{
    char *p;
    int Size ;
    int length;
};
int main()
{
 st s;
 cout<<"Welcome to the String as an ADT program\n";
 cout<<"Enter the maximum size of the string \n";
 cin>>s.Size;
 char str[s.Size];
 cout<<"Enter your string \n";
 gets(str);
 s.p=str;
}

When i run this program there is no compilation error and the program runs fine, it asks me for the size of the string.Once i provide it with an integer number it shows "enter your string" question and exits from the output screen window without me able to enter the string. It happens every time. Kindly point out what is that i am doing wrong?

kaylum
  • 13,833
  • 2
  • 22
  • 31
  • If you are using C++17, then you should probably use `std::string` – NutCracker Apr 08 '20 at 06:27
  • Thanks ardent , how can I allocate memory to that string? can you please ellaborate –  Apr 08 '20 at 06:28
  • The problem is that `operator>>` is not reading the new line character when you read s.SIze. Thus the call to `gets()` is simply reading the new line character. Don't mix `operator>>` and line reading without taking into account the new line. – Martin York Apr 08 '20 at 06:30
  • Hello martin can please show me what to do, I am having a hard time realising my mistake? –  Apr 08 '20 at 06:34
  • @Kay4kartik When you enter the size, for example `22`, then `stdin` actually has `22\n` (that newline character came from your enter key). Only `22` is put into the size variable, and the remaining `\n` remains in the buffer. That is why, `gets` doesn't wait for you to enter a string and press the enter key because it already gets a `\n` from the previous enter key. – Ardent Coder Apr 08 '20 at 06:36
  • okay... so how can I overcome this issue @ArdentCoder ? –  Apr 08 '20 at 06:38
  • @Kay4kartik Use `cin.ignore();` before calling `gets`. This will solve your issue but I don't recommend all this because there are too many problems with your code. `gets` is deprecated, C-style programming using C++, VLA, etc. – Ardent Coder Apr 08 '20 at 06:40
  • thanks so much @ArdentCoder for helping me, other than gets what other function can I use ? should I use getline ? –  Apr 08 '20 at 06:44
  • @Kay4kartik You can google "string manipulation in c++" – Ardent Coder Apr 08 '20 at 11:42

0 Answers0