我的小弟弟目前正在学习如何用c++编程,为了测试数组的不同使用方式,他编写了一个程序,让计算机生成一个随机数,然后根据这个随机数输出一个特定的情感(存储在数组中)。然而,由于某些原因,输出的代码部分不希望按照我建议的方式工作。
我认为应该这样写:'cout <<"我"& lt; & lt;情绪[x] & lt; & lt;',我确信这在过去对我有效,但由于某种原因,计算机不接受这一点。我已经有一段时间没有用c++写代码了,所以可能有些事情发生了变化,或者我忘记了'cout'是如何工作的。
这可能是一些超级简单和愚蠢的东西,我应该已经发现了,但我就是看不出来。下面是剩下的代码,以防问题出现在代码行的更上面的地方。
#include <iostream>
#include <ctime>
#include <fstream>
using namespace std;
string emotion[6];
int main() {
emotion[0] = "Happy";
emotion[1] = "Sad";
emotion[2] = "Angry";
emotion[3] = "Fearful";
emotion[4] = "Disgusted";
emotion[5] = "Suprised";
srand(time(NULL));
int x;
x = (rand() % 6);
cout << "I'm " << emotion[x] << endl;
system("PAUSE");
}
和你想的一样,确实是个小错误。您需要#include <string>
才能按预期工作,这就是为什么。
对于srand
和rand
,您可能还需要#include <cstdlib>
,以下是您可能不需要它的原因。