我知道很多人之前都遇到过这个错误,但我刚开始用C ++编程,所以我对大多数命令还不太确定。
我正在尝试使用以下源代码创建程序:
#include <iostream>
int main()
{
char input[7];
std::cout << "Enter your gender (male or female):";
std::cin.getline (input, 6);
if (input == "male")
char reply[] = "Mr";
else
char reply[] = "Mrs";
std::cout << "Hello " << reply << "!\n";
return 0;
}
现在我尝试用我的编译器(G ++)编译它。我收到了这个错误:
StringTest.cpp: In function 'int main()':
StringTest.cpp: 16:26: error: 'reply' was not declared in this scope
您能否告诉我我的代码到底出了什么问题?我该如何尝试解决它?
谢谢你, Xarlexus
答案 0 :(得分:3)
如果添加(可选)大括号,则更清楚一点:
if (input == "male")
{
char reply[] = "Mr";
}
else
{
char reply[] = "Mrs";
}
std::cout << "Hello " << reply << "!\n";
reply
在}
处不再存在,它结束了声明它的块。所以,在这里,当您尝试打印它时,reply
不存在。
这里的解决方案是在块之外声明reply
,然后从块中分配给它:
char const* reply(0);
if (input == "male")
{
reply = "Mr";
}
else
{
reply = "Mrs";
}
std::cout << "Hello " << reply << "!\n";
这样,当你打印它时,reply
仍然在最后一行的范围内(并且仍然存在)。
但请注意,虽然您的程序现在可以编译,但仍然不正确。 input == "male"
没有按照您的想法执行:input
和"male"
成为指向C字符串的指针,并且比较指针,而不是指向字符串的内容。您需要使用字符串比较函数,或者更好的是,使用std::string
,它会重载==
以使字符串比较语义。
程序的更清晰,更正版本可能如下所示:
#include <iostream>
int main()
{
std::string input;
std::cout << "Enter your gender (male or female):" << std::endl;
if (!std::getline(std::cin, input))
{
std::cout << "Oops, something bad happened during input!" << std::endl;
return 0;
}
std::string reply;
if (input == "male")
{
reply = "Mr";
}
else if (input == "female")
{
reply = "Mrs";
}
else
{
std::cout << "Your selection was invalid" << std::endl;
return 0;
}
std::cout << "Hello " << reply << "!" << std::endl;
return 0;
}
答案 1 :(得分:0)
reply
存在于if / else块范围内的本地。要在它们之外访问它,您必须在该范围之外声明它。
#include <iostream>
#include <string>
int main()
{
std::string input;
std::cout << "Enter your gender (male or female):";
stdgetline(cin, input);
std::string reply;
if (input == "male") {
reply = "Mr";
}
else {
reply = "Mrs";
}
std::cout << "Hello " << reply << "!\n";
return 0;
}
请注意,原始代码中的此代码段不符合您的预期:if (input == "male")
。当你打算比较字符串时,你正在比较指针。最好使用std::string
甚至strcmp
。
答案 2 :(得分:0)
每个if / else语句都有一个隐式块,所以你的代码是:
if (input == "male") {
char reply[] = "Mr";
} else {
char reply[] = "Mrs";
}
// reply is not defined in this scope
你真正想要的是更像这样的东西:
const char *reply;
if (input == "male")
reply = "Mr";
else
reply = "Mrs";
虽然我个人会这样写:
const char * reply = (input == "male") ? "Mr" : "Mrs";
另请注意,我会使用const char *
而不是char []
,因为我认为典型的用法是不可变的字符串,而不是可变的char []。
答案 3 :(得分:0)
input == "male
是无意义的比较,因为它永远不会是真的。 input
是一个数组,并将衰减到第一个元素的指针。从那以后,它的指针比较(即input
和"male"
在同一地址?),这是不正确的。
您需要std::string
代替:
#include <iostream>
#include <string> // <== add this
int main()
{
std::string input; // <== change type of 'input'
std::cout << "Enter your gender (male or female):";
std::getline(std::cout, input); // <== use free function version
char const* reply;
if (input == "male") { // <== now does the correct comparision
reply = "Mr";
}
else {
reply = "Mrs";
}
std::cout << "Hello " << reply << "!\n";
return 0;
}