【问题标题】:Re-enter text to a string将文本重新输入到字符串
【发布时间】:2015-09-03 15:21:41
【问题描述】:

这是我的基于文本的聊天应用程序的源代码。

#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

我无法输入新问题。 我该怎么办 ?

谢谢

【问题讨论】:

  • 我会使用循环而不使用goto
  • 在读完 ques 后尝试刷新标准输入(fflush(stdin),因为你使用 C 函数),也许有些字符留在缓冲区中,当你应该提供更多输入时会被读取
  • 调试代码时,ch的值是多少?
  • 这里只是猜测,但我建议在"So, What do you have in mind ? " 的末尾添加一个换行符(“\n”)。例如,"So, What do you have in mind ? \n"

标签: c++ string goto


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    cin&gt;&gt;ch;之后使用flush

    喜欢这个:

    cin >> ch;
    fflush(stdin);
    

    我建议您阅读此内容(包括里面的链接): How to clear the input buffer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-11
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多