我如何摆脱这种做同时循环

How do I get out of this do-while loop?

本文关键字:循环 何摆脱      更新时间:2023-10-16

我正在尝试创建一个程序,该程序可以输入一串字符,对其进行验证,然后对其进行排序并打印出来。

我确定这里的某个地方存在明显的逻辑错误,有人可以帮忙指出吗?我花了几个小时盯着屏幕。我在有限的C++知识中尝试了我所知道的一切,但我仍然无法让事情发挥作用。

你能提供的任何东西都会以某种方式帮助我,即使是居高临下。

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void mySort(string &s);
int main()
{
    string str;
    char c;
    bool invalid = true;
    cout<<"Please enter some alphabetical characters:"<<endl;
    cout<<"(* to end input): ";
    do
    {
      getline(cin, str, '*');
      for(int i = 0; i < str.length(); i++)
      {
        c = str.at(i);
      }
      if(! ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) ) )
      {
         cout<<"Error!"<<endl;
      }
      else
      {
        (invalid==false);
        cout<<"You entered: "<<str<<endl;
        mySort(str);
      }
    } while(invalid==true);
    system("PAUSE");
    return(0);
}
void mySort(string &s)
{
    sort(s.begin(), s.end());
    cout<<"The string after sorting is: "<<s<<endl;
}

我几乎可以肯定验证的问题出在这一行:

if(! ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) ) )

我敢肯定我的布尔值也是错误的。

任何事情,

任何事情,我都因为这个而浪费了几个小时的头撞墙。

除了true之外,您从未将invalid设置为任何内容。

这一行:

(invalid==false);

应该是:

invalid = false;

前一个版本将invalidfalse进行比较,然后丢弃比较结果。什么都没有改变。

(invalid==false); 应该invalid=false;

第一个更改:

(invalid == false);
invalid = false;

正如其他人所说,您没有正确分配invalid变量。 您也没有正确验证输入字符串。 循环遍历整个字符串,然后仅验证看到的最后一个字符,而不是在循环时验证每个字符。

我建议重写循环以摆脱invalid变量并修复验证,例如:

int main()
{
    string str;
    char c;
    do
    {
        cout << "Please enter some alphabetical characters:" << endl;
        cout << "(* to end input): ";
        if (!getline(cin, str, '*'))
            break;
        if (str.empty())
            cout << "You did not enter anything!" << endl;
        else if (str.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") != string::npos)
            cout << "Error! Bad input" << endl;
        else
        {
            cout << "You entered: " << str << endl;
            mySort(str);
            break;
        }
      }
    }
    while (true);
    system("PAUSE");
    return 0;
}