0
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int main()
{
    char ch;
    do
    {
      char str[80];
      cout<<"\nEnter The String\n";
      gets(str);
      int len=strlen(str);
      for(int i=0;i<len;i++)
      cout<<str[i];
      cout<<"\nContinue?\n";
      cin>>ch;
   }
    while(ch=='y' || ch=='Y');
   getch();
   return 0;
 }

On executing the above program, the loop asks "Continue?" only once and after that it skips the whole code in the do-while loop and goes to the statement of "Continue?". Please tell me what is the mistake??

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by anuj_sharma
0

The problem is that calling "cin >> ch;" will wait for the enter to be pressed, then will read the first char. This will leave the newline or '\n' character on the input stream, so the next time you do gets() to read the line, it will grab the '\n' on the input stream and assume a line was entered. Since the str is empty (or only \n), it will output an extra newline before asking to continue, and again the same cycle repeats. You should use something that will get the '\n' character in the "Continue?" prompt, not a single char. For example, this will work (I don't have conio.h so I have removed those, and you probably should too because it is not standard or portable):

char str[80];
    do
    {
      cout<<"\nEnter The String\n";
      cin.getline(str,80);
      int len=strlen(str);   // ----
      for(int i=0;i<len;i++) // these lines are useless, you can print the string back with just "cout << str;"
        cout<<str[i];        // ----
      cout<<"\nContinue?\n";
      //cin>>ch;
      cin.getline(str,80);
   }
    while(str[0]=='y' || str[0]=='Y');

Edited by mike_2000_17: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.