我正在开发一个程序,假设要求用户输入一个词,然后用 CIAO 翻译它。但是,当我的程序编译时,它只处理第一个字母到我的 switch 语句中的单词长度的次数。我使用什么功能?
#include<iostream>
using namespace std;
int main()
{
//Identify Variables
string word;
int counter;
char letters, word1, word3;
//Ask user to input a word to be translated into I.C.A.O
cout<<" Enter a word: ";
cin>>word;
counter = word.length(); //Counts the number of characters the user inputed
word1 = word[0]; //Converts a string to a char value
//Use a while statement to repeat until there are zero letters to process
while(counter != 0)
{
//Use a switch statement to translate each letter into I.C.A.O
switch(word1)
{
case 'a': case 'A': cout<<"Alpha\n"; break;
case 'b': case 'B': cout<<"Bravo\n"; break;
case 'c': case 'C': cout<<"Charlie\n"; break;
case 'd': case 'D': cout<<"Delta\n"; break;
case 'e': case 'E': cout<<"Echo\n"; break;
case 'f': case 'F': cout<<"Foxtrot\n"; break;
case 'g': case 'G': cout<<"Golf\n"; break;
case 'h': case 'H': cout<<"Hotel\n"; break;
case 'i': case 'I': cout<<"India\n"; break;
case 'j': case 'J': cout<<"Juliet\n"; break;
case 'k': case 'K': cout<<"Kilo\n"; break;
case 'l': case 'L': cout<<"Lima\n"; break;
case 'm': case 'M': cout<<"Mike\n"; break;
case 'n': case 'N': cout<<"November\n"; break;
case 'o': case 'O': cout<<"Oscar\n"; break;
case 'p': case 'P': cout<<"Papa\n"; break;
case 'q': case 'Q': cout<<"Quebec\n"; break;
case 'r': case 'R': cout<<"Romeo\n"; break;
case 's': case 'S': cout<<"Sierra\n"; break;
case 't': case 'T': cout<<"Tango\n"; break;
case 'u': case 'U': cout<<"Uniform\n"; break;
case 'v': case 'V': cout<<"Victor\n"; break;
case 'w': case 'W': cout<<"Whiskey\n"; break;
case 'x': case 'X': cout<<"X-Ray\n"; break;
case 'y': case 'Y': cout<<"Yankee\n"; break;
case 'z': case 'Z': cout<<"Zulu\n"; break;
}
counter--;
}
return 0;
}
最佳答案
您永远不会在循环中修改 word1
,因此 switch 语句将始终选择您在循环之前对其进行初始化的第一个字母。
正确的做法是像这样遍历单词中的字符:
for (char c : word)
{
switch (c) {
//...
}
}
如果您使用的编译器不支持 C++11 功能,例如基于范围的循环(上面使用的),您可以使用 oldskool:
for (size_t i = 0; i < word.size(); i++) {
switch(word[i]) ...
}
或者:
for (std::string::const_iterator it = word.cbegin(); it != word.cend(); it++) {
switch(*it) ...
}
关于c++ - 我使用什么函数来在 cin 语句中存储单个字符,以便我可以单独处理每个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55175594/