如何使用布尔值来验证我的函数?

时间:2015-01-31 09:29:21

标签: c++ validation storage

基本上我想验证这段代码。我试图将它放在main函数中,但它没有循环回输入。例如,如果您以错误的形式输入了注释或以数字开头,我在代码中有一个if语句告诉用户错误......

但它跳过了第二个输入,而不是让用户重新输入他们的音符,但我被告知我需要使用布尔值来验证但我实际上不知道如何使用布尔很好所以解释如何将它正确地链接到函数将是有帮助的,并且作为评论已经提出了几个问题(例如//问题:.....)

问题:在这种情况下,我怎能不重复此代码来验证贝司音符notenameB

bool validatenotename (string notenameM)
    {
        if (notenameM.length() != 2 && notenameM.length() != 3)
        {
            cout<<"invalid number of characters, note must be between 2 or 3 characters (example: A1 or C#2) : \n";
            return false;
        }
        else if (notenameM[0] != "a" && notenameM[0] != "b" && notenameM[0] != "c" && notenameM[0] != "d" && notenameM[0] != "e" && notenameM[0] != "f" && notenameM[0] != "g")
        {
            cout<<"First character of a note should be one of the following (A,B,C,D,E,F,G) \n";
            return false;
        }
        //question: here i want to enter an if statement making sure that when the user enters c#,d#,f#,g#,or a# it will only allow those notes to be 3 characters (the third being a number for octaves) and also the user cant put a b# or e#?
        else if (
    }
do
{


cout << endl
<< " 1) Melody.\n"
<< " 2) Bass.\n"
<< " 3) Playback Melody.\n"
<< " 4) Playback Bass.\n"
<< " 5) Exit.\n"
<< " Choose one of the above and enter the corresponding number then press enter:  ";
cin >> choice;

switch (choice)
{
case 1: 

    { 
        string notenameM;
        int numbernotesM;
        float notelengthM;
        string notename;


        cout<<"Enter number of notes you want: ";
        cin>>numbernotesM;

        for( int i=0; i < numbernotesM; i++)
        {
            cout<<"Enter note"<<i+1<<": ";
           cin>>notenameM;


        }


        for( int i=0; i < numbernotesM; i++)
        {
            cout<<"enter note length for "<<i+1<<": \n";
            cin>>notelengthM;

        }


    }

break;

case 2:
    {
        string notenameB;
        int numbernotesB;
        float notelengthB;
        string notename;

        cout<<"Enter number of notes you want: \n";
        cin>>numbernotesB;

            for( int i=0; i < numbernotesB; i++)
        {
            cout<<"Enter note"<<i<<": \n";
        cin>>notenameB;
        }

        for( int i=0; i < numbernotesB; i++)
        {
            cout<<"enter note length for "<<i<<": \n";
            cin>>notelengthB;
        }
    }
break;

1 个答案:

答案 0 :(得分:1)

在以下声明中:

else if (notenameM[0] != "a" && notenameM[0] != "b" && notenameM[0] != "c"
        && notenameM[0] != "d" && notenameM[0] != "e" && notenameM[0] != "f" 
        && notenameM[0] != "g")

notenameM[0]只是一个字符,您试图将其与字符串进行比较,即"a"实际上是一个字符串,其中包含存储在内存中的额外空终结符| a | \0 |。像'a'一样更改所有内容。