我正在为我的计算机科学课程做作业。我们的目标是制作一个程序来简化非常通用的指令集,以将竖琴调整为更易读的术语。
例如:ATB+3 将变为:ATB 收紧 3。 或者:ATB-6 会变成:ATB 放松 6。
我的计划是使用 at() 函数使用其结果将字母添加到字符串中。这是我的代码:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
string instructions;
string firstLetters = "";
string tightenOrLoosen;
int plusSign;
int minusSign;
int indexCount;
char repeatDecision = 'y';
char number = '0';
int main()
{
while (repeatDecision == 'y' || repeatDecision == 'Y') {
cout << "Hello! Please enter the harp tuning instructions here: ";
cin >> instructions;
plusSign = instructions.find("+");
minusSign = instructions.find("-");
if (plusSign == -1 && minusSign == -1) {
cout << "Make sure there is a plus or minus symbol in your instructions." << endl << endl;
} else if (plusSign != -1){
tightenOrLoosen = "tighten";
for (int i = 0; i > plusSign; i++) {
firstLetters = firstLetters + instructions.at(i);
cout << firstLetters;
}
number = instructions.at(indexCount);
} else {
tightenOrLoosen = "loosen";
for (int i = 0; i >= minusSign; i++) {
firstLetters = firstLetters + instructions.at(i);
indexCount = i;
cout << firstLetters;
}
number = instructions.at(indexCount);
}
if(plusSign != -1 || minusSign != -1) {
cout << firstLetters << " " << tightenOrLoosen << " " << number << endl << endl;
}
}
return 0;
}
问题是我的 for 循环似乎没有向“firstLetters”字符串添加任何内容。我在循环时检查了结果,这确认了字母没有被添加到字符串中。我确信这是一个非常简单的错误,而且我绝对是一个初学者程序员,但任何提示将不胜感激。谢谢。
您的作业似乎涉及从标准流读取输入并解析它。这需要将输入分解为标记并确定它是否与预期格式匹配。在您的情况下,输入由三个不同的部分(标记)组成:
Location:第一个标记表示字符串的位置(例如“ATB”,我将其解释为“在和弦 B”)。根据上下文和没有附加信息,我假设这部分仅由字母组成。
方向:第二个标记指定调谐销必须旋转的方向。
Amount:第三个标记表示调音销应旋转的角度。
代币预计按以下顺序出现:位置、方向、金额。
挑战在于正确阅读和解释每个部分。这是一种可能的方法:
#include <iostream>
#include <string>
using namespace std;
int main()
{
// read the note and direction (reads until a non-alpha character is extracted;
// the last read character will be stored in 'c')
string location;
char c; // after the loop ends, 'c' will contain the direction (if the input is correct)
while (c = '*', cin.get(c) ) // initialize 'c' with an invalid character, then read the next character. if the read operation fails, the loop terminates.
{
if (isalpha(c)) // if the read charcter is a letter, add it to the location string; otherwise, break the loop
location += c;
else
break;
}
// todo: validate 'location', if requested
// convert the direction
string direction;
switch (c)
{
case '-':
direction = "loosen";
break;
case '+':
direction = "tighten";
break;
default:
cout << "+ or - expected" << endl;
return -1;
}
// read the amount
int amount;
if (!(cin >> amount))
{
cout << "number expected" << endl;
return -2;
}
// convert
cout << location << ' ' << direction << ' ' << amount << endl;
}