【发布时间】:2015-01-31 09:29:20
【问题描述】:
基本上我想验证这段代码。我试图把它放在主函数中,但它没有循环回输入。例如,如果您以错误的形式输入注释或以数字开头,我在代码中有一个 if 语句告诉用户错误......
但它跳到第二个输入而不是让用户重新输入他们的笔记,但我被告知我需要使用布尔值来验证但我实际上不知道如何很好地使用布尔值所以解释如何将它正确链接到函数会很有帮助,并且已经将几个问题作为 cmets 放入(例如 // question:.....)
问题:在这种情况下,我如何才能不重复此代码来验证 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;
【问题讨论】:
-
发帖前请去掉所有不必要的代码。
-
我不太确定什么是不必要的,我认为我只放了我认为重要的代码?
-
例如,任何输入似乎都是不必要的。您可以硬编码您设想用户输入的值。
-
这就是我对输入感到非常困惑的原因,这就是为什么我将它保留在那里我假设我们正在谈论 consol 输入我想知道这些 CIN 函数是否按顺序存储输入?使用向量也会更有效吗?因为我想构建程序以最终向用户发出提示音
-
你的函数需要一个字符串,它并不关心这个字符串来自哪里。
标签: c++ validation storage