首页 > 解决方案 > 字符串和开关语句有问题??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;
      }
    }
 }

标签: c++stringif-statementswitch-statement

解决方案


if (atzime[1] == '-' || '+')

这并不像你认为的那样。

((atzime[1]=='-') || '+') 因此,如果第一个测试失败,则第二个测试'+'本身就是true. 所以总是这样true

您需要将其写为: (atzime[1] == '-' || atzime[1] == '+')

同时,我认为您随后的switch陈述与任何内容都不匹配。您似乎期待一个以字母开头的字符串,然后是 a +or -。因此,如果您键入,例如"A+"散列将不匹配,"+"也不匹配"-"本身。


推荐阅读