c++ - 字符串和开关语句有问题??C++评分系统
问题描述
当我开始编写这段代码时,我遇到了字符串和 switch 语句的问题,这就是为什么我不确定我是否正确绕过了这个问题。主要问题是程序打印仅针对图表而不是字符串确定。也许那是因为使用了错误的“如果”。这是我的代码:
#include <iostream> #include <string> using std::cin; using std::cout; using std::string; using namespace std; constexpr long long string_hash(const char *s) { long long hash{}, c{}; for (auto p = s; *p; ++p, ++c) { hash += *p << c; } return hash; } constexpr long long operator"" _sh(const char *s, size_t) { return string_hash(s); } int main() { cout << "Ievadiet atzimi ar burtiem (A, B, C, D, F) ==> "; string atzime; char burts; double atzime_sk, pluss, minuss; cin >> atzime; burts = atzime[0]; switch(burts) { case 'A': atzime_sk = 4; cout << "Tava atzime ir ==> " << atzime_sk; break; case 'B': atzime_sk = 3; cout << "Tava atzime ir ==> " << atzime_sk; break; case 'C': atzime_sk = 2; cout << "Tava atzime ir ==> " << atzime_sk; break; case 'D': atzime_sk = 1; cout << "Tava atzime ir ==> " << atzime_sk; break; case 'F': atzime_sk = 0; cout << "Tava atzime ir ==> " << atzime_sk; break; default: break; } if (atzime[1] == '-' || '+') { switch (string_hash(atzime.c_str())) { case "+"_sh: pluss = atzime_sk + 0.3; cout << "Tava atzime ir ==> " << atzime_sk; break; case "-"_sh: minuss = atzime_sk - 0.3; cout << "Tava atzime ir ==> " << atzime_sk; break; default: break; } } }
解决方案
if (atzime[1] == '-' || '+')
这并不像你认为的那样。
((atzime[1]=='-') || '+')
因此,如果第一个测试失败,则第二个测试'+'
本身就是true
. 所以总是这样true
。
您需要将其写为: (atzime[1] == '-' || atzime[1] == '+')
同时,我认为您随后的switch
陈述与任何内容都不匹配。您似乎期待一个以字母开头的字符串,然后是 a +
or -
。因此,如果您键入,例如"A+"
散列将不匹配,"+"
也不匹配"-"
本身。
推荐阅读
- react-native - 世博会在Android上反应原生MapView的问题
- javascript - HTML Canvas 因任何原因无法正常工作
- sql - 不在聚合函数或 group by 子句中:语句中的 org.hsqldb.Expression@59bcb2b6
- php - Drupal 8 通过 REST API 更新用户资料图片
- python - 缺少 os.walk() 的文件
- jquery - 无法在 Django 视图函数中检索 AJAX 请求数据值
- ios - Swift UI 和阴影颜色
- angular - 如何立即修复导出的 unix
- javascript - 如何使用 javascript 将字符串转换为 base_64?
- linux - 在 shell 脚本中出现意外标记“fi”附近的语法错误