标识字符串
Identifying strings
好的,所以我在中级编程课上,我们正在使用C++。但是在入门课上,我们学习了python。话虽如此,我根本不知道C++。我已经做了很多搜索并尽力设置这个程序,但我就是无法让它正常工作。似乎我已经解决了"标识符"未定义"错误,我不知道如何解决它们。 该程序应该接受输入的电子邮件并检查其格式是否正确。
我的老师建议这样做: "要进行验证,请检查 c++ 中定义的字符串变量。 看看 允许您搜索字符串以查找字符的方法。 还看 在创建字符串的字符串方法中。 您应该能够搜索 @ 的字符串并创建部件的子字符串。 然后验证零件。
请帮忙!
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class emailverify
{
public: // global variables/functions
std::string test;
std::string email;
std::string at = "@";
std::string period = ".";
};
int main()
{
std::string test = "Y";
while (test == "Y" || test == "y") // while loop to keep asking for more emails if the user wishes to test another
{
cout << "Please enter a valid Email address.n"; // asks for email
cin >> email;
if (email.find(at != std::string::npos))
{
if (email.find_last_of(period != std::string::npos))
{
cout << "This email is valid. Would you like to try another? (Y/N)n"; // email passed both tests, so is valid, seeing if while loops continues or not
cin >> test;
}
else
{
cout << "This email is invalid, would you like to try another? (Y/N)n"; // failed second test, so is not valid, seeing if while loop continues or not
cin >> test;
}
}
else
{
cout << "This email is invalid, would you like to try another? (Y/N)n"; // failed first test, so is not valid, seeing if while loop continues or not
cin >> test;
}
} // while loop ends
return 0;
}
您似乎对变量在C++中的工作方式感到困惑。
使用 GCC 编译您的程序时,它说:
test.cpp: In function ‘int main()’:
a.cpp:23:20: error: ‘email’ was not declared in this scope
cin >> email;
这意味着没有名为email
的变量。您在emailverify
类中声明了一个具有该名称的成员变量,但仅当您定义类型为emailverify
的变量时才使用该变量,并且您没有这样做。
现在,我建议你去掉emailverify
类,直接将你需要的变量声明为main
中的局部变量(你可以将它们声明为全局变量,但最好将它们保留在本地):
int main()
{
std::string test;
std::string email;
std::string at = "@";
std::string period = ".";
然后还有一堆其他错误,例如email.find(at != std::string::npos)
而不是email.find(at) != std::string::npos
,但你最终会得到这些错误。
PS:我知道一些编程老师喜欢编写代码,例如std::string at = "@";
但恕我直言,这很愚蠢。写email.find("@")
是完全可以的,额外的变量不会给你买任何东西。
您的问题出在代码的一部分:
class emailverify
{
public: // global variables/functions
std::string test;
std::string email;
std::string at = "@";
std::string period = ".";
};
它不定义全局变量或函数,但声明类。主函数中没有电子邮件或测试变量,既未定义也未声明。
如果你想坚持全局,你可以做的是创建 emailverify 类型的全局对象并通过.
使用其成员,或者通过::
(emailverify::test
) 使它们static
和访问,或者将class
更改为namespace
,但它也需要在类之外定义它们(在C++中定义静态成员)。
但是,您可以将他们用作当地人,现在不必担心所有这些。