我遇到了一些我写过的代码问题。
我用c ++编写,我正在尝试设置3个字符串,所有字符串都是“关闭”。我也试图在程序开始时将2个布尔值设置为false
。所有这些开始代码都有效。
我想设置一个if语句,这样如果布尔值同时都是true
,那么所有的字符串都会变为“on”,然后程序会输出一个输出结果他们在。
我已经在网上看了,但找不到答案,所以如果你有任何想法,我真的很感激一些帮助。
谢谢!
以下是供参考的代码:
//imports the required utilities for the program
#include <iostream>
#include <string>
using namespace std;
//sets up the main method
int main()
{
//declares and assigns all variables needed for program
string light1 = "off";
string light2 = "off";
string electricity = "off";
bool power(false);
bool pressure(true);
//prints the outcome to indicate that the electricity is off to begin with
std::cout << ("The Electricity is " + electricity +", Light #1 is "+
light1 +" and Light #2 is "+ light2 +".");
//introduces if statement to turn on electricity in lights
if ((power) && (pressure))
{
string light1 = "on";
string light2 = "on";
string electricity = "on";
}
//prints the new outcome to indicate if the electricity is on
cout << "\n";
std::cout << ("The Electricity is " + electricity +", Light #1 is "+
light1 +" and Light #2 is "+ light2 +".");
}
答案 0 :(得分:2)
您声明了三个仅存在于该if语句范围内的新字符串变量。删除数据类型以将值赋给if语句之外的字符串,如此
if ((power) && (pressure))
{
light1 = "on";
light2 = "on";
electricity = "on";
}
答案 1 :(得分:0)
修复如下。不要在if语句中重新声明变量,C ++有一个范围的概念,有关这方面的更多内容http://en.cppreference.com/w/cpp/language/scope。另外,在实现文件的顶部添加QThread
被认为是非常糟糕的(对于像你这样的小例子来说这很好,但是对未来要小心)
using namespace std;