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

Recommended Answers

All 2 Replies

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');

Thanks a lot Mike. I got the solution and also learned somehting new.

:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.