这是我为了将英语转换成摩尔斯电码而变得有趣的项目
我还是初学者,我自己学习c ++,所以如果问题很愚蠢,我很抱歉,但我没有其他人要求
问题是关于第17行
任何想法为什么它不称它并重新开始?
代码:
#include <iostream>
using namespace std;
string morse [26] { ".-", "-...", "-.-.", "-..", ".", "..-." , "--." , "....", "..",
".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...",
"-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
char alphabet [26] {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
void convert();
int main (){
convert();
cout << "\nExit ?(y/n)\n";
char ans;
cin >> ans;
if (ans=='y') return 0;
if (ans=='n') convert();} //line 17
void convert () {
string input ;
int i=0 ;
cout << "Enter your text :\n";
getline(cin,input);
for (i;i < input.length() ;i++) {
string text = input;
if (text[i] == alphabet[0]) {cout << morse[0] << " ";}
if (text[i] == alphabet[1]) {cout << morse[1] << " ";}
if (text[i] == alphabet[2]) {cout << morse[2] << " ";}
if (text[i] == alphabet[3]) {cout << morse[3] << " ";}
if (text[i] == alphabet[4]) {cout << morse[4] << " ";}
if (text[i] == alphabet[5]) {cout << morse[5] << " ";}
if (text[i] == alphabet[6]) {cout << morse[6] << " ";}
if (text[i] == alphabet[7]) {cout << morse[7] << " ";}
if (text[i] == alphabet[8]) {cout << morse[8] << " ";}
if (text[i] == alphabet[9]) {cout << morse[9] << " ";}
if (text[i] == alphabet[10]) {cout << morse[10] << " ";}
if (text[i] == alphabet[11]) {cout << morse[11] << " ";}
if (text[i] == alphabet[12]) {cout << morse[12] << " ";}
if (text[i] == alphabet[13]) {cout << morse[13] << " ";}
if (text[i] == alphabet[14]) {cout << morse[14] << " ";}
if (text[i] == alphabet[15]) {cout << morse[15] << " ";}
if (text[i] == alphabet[16]) {cout << morse[16] << " ";}
if (text[i] == alphabet[17]) {cout << morse[17] << " ";}
if (text[i] == alphabet[18]) {cout << morse[18] << " ";}
if (text[i] == alphabet[19]) {cout << morse[19] << " ";}
if (text[i] == alphabet[20]) {cout << morse[20] << " ";}
if (text[i] == alphabet[21]) {cout << morse[21] << " ";}
if (text[i] == alphabet[22]) {cout << morse[22] << " ";}
if (text[i] == alphabet[23]) {cout << morse[23] << " ";}
if (text[i] == alphabet[24]) {cout << morse[24] << " ";}
if (text[i] == alphabet[25]) {cout << morse[25] << " ";}
if (text[i] == alphabet[26]) {cout << morse[26] << " ";}
if (text[i] == ' ') {cout << " / "; }
}
}
答案 0 :(得分:1)
您的代码中存在一些问题,但是关于程序没有循环的原因,那是因为您没有告诉它循环,您只能告诉它调用转换()第二次。
int main (){
convert(); // first call
cout << "\nExit ?(y/n)\n";
char ans;
cin >> ans;
if (ans=='y') return 0;
if (ans=='n') convert(); //line 17
// program ends
}
这里有一个次要问题,你只读了ans
的一个字符,这意味着你没有读过&#34; \ n&#34;行尾,因此getline()
内的convert
会认为有一个空行。
您可能想尝试:
int main()
{
bool quitting = false;
while (!quitting)
{
convert();
std::cout << "\nExit? (y/N): " << std::flush;
std::string ans = "";
std::getline(std::cin, ans);
if (!ans.empty() && (ans[0] == 'y' || ans[0] == 'Y'))
quitting = true;
}
}