0

Here's my source code for a text based chatting app.

#include <iostream>
#include<iomanip>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#include<time.h>
#include<ctype.h>
using namespace std;


int main()
{
    time_t mytime;
    mytime = time(NULL);
    char ques[100],ch;
    cout<<setw(75)<<"Welcome To Talk Back\n\n";
    start:
    cout<<"So, What do you have in mind ? ";
    gets(ques);
                for(int i=0;ques[i]!=0;i++) //Convert string to uppercase
                    ques[i]=toupper(ques[i]);

    //puts(ques);
    for (int i =0;ques[i]!=0;i++)
    {
        if((ques[i]=='T')&&(ques[i+1]=='I')&&(ques[i+2]=='M')&&(ques[i+3]=='E'))
            cout<<"\n\nThe Time and Date as of now is  : "<<ctime(&mytime);
    }

    puts(ques);
    cout<<"Anything Else ? Y/N ";
    cin>>ch;
    if(ch=='Y'||ch=='y')
        goto start;
    else
        exit(0);
    return 0;
}

The Problem : When i try to ask a new question from thye user via using the goto statement to restart the code, here's what happens : http://prntscr.com/8c5yif

I can't enter a new question. What should I do ?

Thanks

NathanOliver
  • 171,901
  • 28
  • 288
  • 402

2 Answers2

0

With std::cin and std::cin::clear it's working.

Live demo

#include <iostream>
#include <algorithm>
#include<iomanip>
#include<stdlib.h>
#include<string.h>
#include <string>
#include<stdio.h>
#include<time.h>
#include<ctype.h>
using namespace std;

int main()
{
    time_t mytime;
    mytime = time(NULL);
    std::string ques, answer;

    cout << setw(75) << "Welcome To Talk Back\n\n";

    do
    {
        cout << "So, What do you have in mind ? ";
        std::getline (std::cin, ques);
        std::cin.clear();

        //Convert string to uppercase
        for (auto& character : ques)
        {
            character = toupper(character);
        }

        if (ques.find("TIME") != std::string::npos)
        {
            cout<<"\n\nThe Time and Date as of now is  : "<< ctime(&mytime);
        }

        std::cout << ques << std::endl;

        cout<<"Anything Else ? Y/N " << std::endl;
        std::getline (std::cin, answer);
        std::cin.clear();
        std::cout << "Reply: " << answer << std::endl;
    }
    while ("Y" == answer || "y" == answer);

    return 0;
}
Richard Dally
  • 1,432
  • 2
  • 21
  • 38
0

Use flush after cin>>ch;

Like this one:

cin >> ch;
fflush(stdin);

And I recommend you to read this (including links inside): How to clear the input buffer

Community
  • 1
  • 1
StahlRat
  • 1,199
  • 13
  • 25