-10

I am new to programming and I can only use C++. I have been working on an RPG, and for some reason I can't get the program to print out the value that I set a string to. I started by defining the string "weapon" in void main.

void main()
{
string weapon;
cin >> weapon;
if(weapon = "A")
{
weapon == "sword";
}
}

I had the code sort of like this and I had a function above it that uses "weapon" (which was set to sword as you can see from the code above) at the end of something that I had it print out, but that was in the function (which was above the void main) so in order to get both to be defined variables I had to define them in both the void main and the function, but when I do that, nothing appears in the program when it's run. I had everything written correctly (what I put above is just an example) but the only way that it doesn't create an error is by defining it in both parts of the code. It says that one of them hasn't been defined yet so I defined it both the function and the void main. Why isn't it working? How do I fix it? Thanks

P.S. I did include the string library and namespace.

4

4 回答 4

6

void main()是非法的。它必须是int main(),尽管一些编译器会错误地接受void main()

if(weapon = "A")
{
weapon == "sword";
}

看起来你有这个倒退。无论用户输入什么,单曲都operator=设置weapon为常量。"A"比较与常数进行operator==比较并立即丢弃该结果。也许您的意思是在 的主体中使用比较和赋值?weapon"sword"ifif

于 2013-07-21T18:40:50.453 回答
5

您在=需要的地方使用,==反之亦然。应该:

if(weapon == "A") { weapon = "sword"; }
于 2013-07-21T18:39:32.577 回答
1

至少在我读到它时,您的代码大致如下:

void f() { 
    string weapon;
    cout << weapon;
}

int main(){ 
    string weapon = "sword";
    f();
}

...问题是您分配给weaponin的值main在您调用f.

假设这大致正确,您看到的是正常的预期行为。weapon您在 中定义的是与您在 中定义main的独立变量。给一个赋值对另一个没有影响。weaponf

要获得所需的效果,您需要将值从一个“传递”到另一个作为参数:

void f(string w) { 
    cout << w;
}

int main() { 
   string weapon = "sword";
   f(weapon);
}

这样,调用会为其分配in已分配f的当前值的副本,因此可以使用相同的值。weaponmainf

于 2013-07-21T18:48:21.677 回答
1

您应该查找在线教程,使用 C++ 编程。这是一个开始的好地方。或者购买一本关于 C++ 编程的书。

于 2013-07-21T23:36:05.300 回答