C++ 为什么赢了';t我的switch语句在我的C++;节目?

C++ 为什么赢了';t我的switch语句在我的C++;节目?,c++,for-loop,switch-statement,break,C++,For Loop,Switch Statement,Break,该程序应该使用星号输出不同长度的垂直线和水平线。星号的数量和方向由用户在输入语句中决定。它必须使用switch语句创建。以下是我当前的代码: int main() { // Variables int length = 1; char direct; // User input choice if (length >= 1 && length <= 20) { cout << "\nEnter t

该程序应该使用星号输出不同长度的垂直线和水平线。星号的数量和方向由用户在输入语句中决定。它必须使用switch语句创建。以下是我当前的代码:

int main() {

    // Variables
    int length = 1;
    char direct;

    // User input choice
    if (length >= 1 && length <= 20) {
        cout << "\nEnter the line length and direction: ";
        cin >> length >> direct;
    }

    // If user input incorrect
    else {
        system("pause");
    }

    // Switch cases for horizontal or vertical
    switch (direct) {
    case 'h': for (int count = 0; count <= length; count++) {
        cout << "*";
        break;
    }
    case 'H': for (int count = 0; count <= length; count++) {
        cout << "*";
        break;
    }
    case 'V': for (int count = 0; count <= length; count++) {
        cout << "*" << "\n" << endl;
        break;
    }
    case 'v': for (int count = 0; count <= length; count++) {
        cout << "*" << "\n" << endl;
        break;
    }

    default:  cout << "Illegal comand" << endl;

    }

    system("pasue");
}
下面是我的一个垂直选择输出语句的样子:

Enter the line length and direction: 4 h
***

*

Illegal Command
Enter the line length and direction: 4 v

*

Illegal Command
下面是我想要的水平面:

Enter the line length and direction: 4 h

****
Enter the line length and direction: 4 v

*
*
*
*
下面是我想要的垂直面:

Enter the line length and direction: 4 h

****
Enter the line length and direction: 4 v

*
*
*
*

为什么星号输出不正确?为什么每次都输出“非法命令”?我还认为我应该注意到,我是初学者,当谈到C++。谢谢

在for循环外部写入break语句。如果在for循环内部写入break语句以防万一,那么它就会从for循环中出来。遇到非法命令,因为您没有在for循环外部使用break

您拥有
break语句位于错误的位置

case 'h': for (int count = 0; count <= length; count++) {
    cout << "*";
    break;
}
您可以类似地组合案例
v
v

您仍然可以通过创建辅助函数来编写水平线和垂直线来改进它

case 'h':
case 'H':
  writeHorizontalLine(length);
  break;

case 'v':
case 'V':
  writeVerticalLine(length);
  break;
在哪里

void writeHorizontalLine(int-length)
{

对于(int count=0;count请尝试在每个切换条件下将break关键字从花括号中去掉

这样做

case 'V': for (int count = 0; count <= length; count++) {
        cout << "*" << "\n" << endl;

    }
break;

case“V”:for(int count=0;count请尝试,如果您这样做,问题应该是显而易见的。提示:
break
语句在哪里?非常感谢!所有这些都帮了大忙:)
case 'V': for (int count = 0; count <= length; count++) {
        cout << "*" << "\n" << endl;

    }
break;
case 'V': for (int count = 0; count <= length; count++) {
            cout << "*" << "\n" << endl;
            break;
        }