如何解决Char to static_cast<int> 有效,但 char[7] to static_cast 无效
我正在为一个班级项目工作,希望我将一串字母转换为数字,我没有使用 switch 语句,因为那会很笨而且太长,所以我做了以下程序。但是,它的问题是我一次只能做一个字母,因为它是一个字符,如果我尝试这样做,static_cast<int>(phrase)
将不起作用:char phrase[7];
它会给我 3错误(我现在不记得它们是什么,我将在今天晚些时候进行编辑以包含错误)。我也不能使用某些代码,比如 stoi 和 atoi,因为我们还没有在我的教科书中讨论它们。因此,如果您可以对这个问题给出多种不同的看法,将不胜感激!谢谢!另外,如果您能确保代码可以与我的程序一起使用,那就更好了!我在代码中留下了 char phrase[7]
,所以如果你想复制和粘贴来查看错误,你可以!任务是让用户输入尽可能多的字母并将其作为 123-1234 返回给他们,因为程序只会使用前 7 个字母(如果您还可以弄清楚如何分解单词以允许破折号(-) 介于两者之间也很酷。)
编辑: 为了使电话号码更容易记住,一些公司使用字母来表示他们的电话号码。例如,使用字母,电话号码 438-5626 可以显示为 GET LOAN。在某些情况下,为了使电话号码有意义,公司可能会使用七个以上的字母。例如,225-5466 可以显示为 CALL HOME,它使用八个字母。编写一个程序,提示用户输入以字母表示的电话号码,并以数字形式输出相应的电话号码。如果用户输入的字母超过七个,则只处理前七个字母。还要在第三个数字后输出 –(连字符)。允许用户同时使用大写和小写字母以及单词之间的空格。特殊字符 –(连字符)代表数字 1,而 _(下划线)代表数字 0。此外,您的程序应该根据用户的需要处理尽可能多的电话号码。 错误:
-
无效的类型转换
-
“char *”类型的参数与“int”类型的参数不兼容
-
表达式必须是可修改的 Ivalue
#include <iostream> #include <string> #include <cctype> using namespace std; int main() { char phrase[7]; char letter; int digit; int num = 0; cout << "Enter Y/y to convert a telephone number from letters to digits" << endl; cout << "Enter any other key to terminate the program." << endl; cin >> letter; while (letter == 'Y' || letter == 'y') { cout << "Enter a telephone number using 7 or more letters" << endl; cout << "for Prefix and number,only the first 7 letters are used." << endl; cout << "and dashes '-' are ZEROES,underscores '_' are ONES" << endl; cout << "ALL OTHER SYMBOLS ARE ignored." << endl; cout << "-->: "; cin >> phrase; cout << endl; phrase = toupper(phrase); num = static_cast<int>(phrase) - static_cast<int>('A'); if (0 <= num && num < 26) { digit = (num / 3) + 2; if (((num / 3 == 6) || (num / 3 == 7)) && (num % 3 == 0)) digit = digit - 1; if (digit > 9) digit = 9; cout << "The corresponding telephone number is: " << digit << endl; cout << "To process another telephone number,enter Y/y" << endl; cout << "Enter any other key to terminate the program." << endl; cin >> letter; } else cout << "Invalid input." << endl; } return 0; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。