2015-09-03 116 views
0

這是我的基於文本的聊天應用程序的源代碼。將文本重新輸入字符串

#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; 
} 

問題: 當我嘗試通過使用goto語句重新啓動代碼詢問從泰豐用戶一個新的問題,這裏發生了什麼:http://prntscr.com/8c5yif

我不能進入一個新的題。 我該怎麼辦?

感謝

+5

我會使用一個循環和不使用'goto' – NathanOliver

+1

嘗試在讀取ques(fflush(stdin),因爲您使用C函數)後刷新標準輸入,也許某些字符留在緩衝區中,並在您應該輸入更多輸入時進行讀取 – Cantfindname

+0

當您調試你的代碼,'ch'的價值是什麼? –

回答

0

隨着std::cinstd::cin::clear它的工作。

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; 
} 
相關問題