【问题标题】:Using cin, if statement, and array not working使用 cin、if 语句和数组不起作用
【发布时间】:2018-12-06 20:03:50
【问题描述】:

我正在用 C++ 制作一个迷你 CPU,它使用数组的二进制状态来激活不同的事件。例如,第 67、39 和第 23 个值为 1 的数组可能会输出日期。我正在做一个输入测试,输入“a”会导致第一个实际值是一个。如您所见,数组已经以“a”开头,但这是 CPU 某个部分的指示符。

我做了错误报告告诉我的所有事情,但他们继续发送相同的结果。如果你愿意,我可以发送调试。

#include <iostream>
using namespace std;

int main() {
    char var a = 1 

    char myArray = {a, 0, 0, 0, 0, 0, 0, 0, 0};

    char var pushregister;  
    cin >> pushregister;

    if (pushregister == a) {
        myArray = {a, 1, 0, 0, 0, 0, 0, 0, 0}
    };

    cout << myArray;

    return 0;
}

【问题讨论】:

  • 这是您的实际代码吗? char myArray = {a, 0, 0, 0, 0, 0, 0, 0, 0};myArray = {a, 1, 0, 0, 0, 0, 0, 0, 0} 甚至不应该编译
  • char var a = 1(除其他外) - 你确定这可以编译吗?
  • 这不是 C++。
  • 看来您需要对 C++ 的语法和规则有良好的基础。
  • 如果你想玩bytes,我推荐使用uint8_t,因为char可以被签名、未签名或char取决于编译器设置。

标签: c++ arrays if-statement cin cpu-registers


【解决方案1】:

你的代码看起来不像 C++。
你想要这样的东西吗?

#include <iostream>
#include <cstdint>
#include <cstdlib>


int main()
{
  uint8_t a = 1;
  uint8_t my_array[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
  static const size_t my_array_capacity =
    sizeof(my_array) / sizeof(my_array[0]);
  my_array[0] = a;

  uint8_t push_register;
  std::cin >> push_register;
  if (push_register == a)
  {
    my_array[1] = 1;
  }

  for (size_t i = 0; i < my_array_capacity; ++i)
  {
    if (i > 0)
    {
      std::cout << ", ";
    }
    std::cout << static_cast<unsigned int>(my_array[i]);
  }
  std::cout << "\n";
  return EXIT_SUCCESS;
}

一些区别:
1. 数组不能包含变量,它们包含值。
2.使用[]访问阵列槽。
3、打印uint8_t时,强制转换为unsigned int,避免cout把变量当作字符。

【讨论】:

  • 一开始我做了第一个,告诉我要添加变量(不是具体但一般,告诉我它们不能只包含值)
【解决方案2】:

代码:

string myArray= "a, 0, 0, 0, 0, 0, 0, 0, 0";
int pushregister; cin >> pushregister;

if (pushregister == a) {
    myArray = "a, 1, 0, 0, 0, 0, 0, 0, 0"; cout << myArray;
}
else {
    cout << "Wrong input" << endl;
}

return 0;

【讨论】:

  • 你可以使用字符串轻松编写这种类型的代码。
  • 我建议 1) 每行一个语句。 2) 编辑时使用 {} 重新格式化。
  • 下次我尝试遵循您的建议。我是初学者。谢谢您的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-16
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 2017-10-22
相关资源
最近更新 更多