自动重复代码

repeat code automatically

本文关键字:代码      更新时间:2023-10-16

我写了一些代码来将任何字符串转换为莫尔斯电码。在我尝试自动重复之前,代码工作得很完美。

无论我使用"while"还是"do while",代码只运行一次,然后终止。你能帮忙找出问题是什么吗?

int main ()
{
    cout<<"Enter the string: ";
    char myStr[81];
    char ch='y';
    while (ch=='Y'||ch=='y')
    {
        getString(myStr);
        toUpper(myStr,strlen(myStr));
        removeSpace(myStr);
        getMorse(myStr,strlen(myStr));
        cout<<"to repeat press Y/y";
        cin>>ch;
    }
    return 0;
}

添加了getString()函数

void getString(char myStr[])
{
  cin.getline(myStr,81,'n');
}

用户输入input后,按回车键。换行字符'n'仍然在cin流中。你需要ignore它:

cin >> ch;
cin.ignore(numeric_limits<streamsize>::max(), 'n'); //this ignores all subsequent characters until the newline character