gpt4 book ai didi

c++ - char变量和if语句错误C++

转载 作者:太空宇宙 更新时间:2023-11-04 13:01:09 25 4
gpt4 key购买 nike

我有以下 for 循环:

string temp;
int responseInt[10][10] = { {0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0}};

for (int i = 0; i < numberPros; i++)
{
for (int j = 0; j < numberRes; j++)
{
cout << "Is " << process[i] << " holding (h), requesting (r), or doing nothing (n) to " << resources[j] << " ?: ";
cin >> temp;
if (temp == 'n')
responseInt[i][j] = 0;
else if (temp == 'h')
responseInt[i][j] == -1;
else if (temp == 'r')
responseInt[i][j] == 1;
}
}

但是,如果 if 语句被忽略,因为 responseInt 的默认值永远不会改变,即使我键入 hrn

我已经尝试过使用字符串,但同样的事情发生了。

如有任何帮助,我们将不胜感激。

最佳答案

这个有效:

#include <string>
#include <iostream>
using namespace std;

int main(){

string temp;
int responseInt[10][10] = { {0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0}};

int numberPros = 2;
int numberRes = 10;

for (int i = 0; i < numberPros; i++)
{
for (int j = 0; j < numberRes; j++)
{
cout << "Is " << i << " holding (h), requesting (r), or doing nothing (n) to " << j << " ?: ";
cin >> temp;
if (temp == "n")
responseInt[i][j] = 0;
else if (temp == "h")
responseInt[i][j] == -1;
else if (temp == "r")
responseInt[i][j] == 1;
}
}
}

您的 cin>>temp 正在读取一个字符串,因此最好使用双引号(例如 "r")而不是单引号将它与字符串进行比较(例如 'r')。

请注意,我必须包含一堆额外的代码才能编译。这应该在您的问题中,作为最小工作示例 (MWE)。

关于c++ - char变量和if语句错误C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44191513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com