向量使用中的致命错误

时间:2015-12-28 03:23:37

标签: string email url

对于学校的c ++实验室(使用microsoft visual studio,因此系统("暂停"))我正在创建一个程序,让用户输入一个电子邮件地址,程序将吐出用户名(在' @'之前)和网站类型,基于地址的最后三个字母(com是商业企业)或最后两个字母的国家代码(我们是美国)。 / p>

#include <iostream>
#include <string>

using namespace std;

void getemail(string &email);
void finduser(string email);
void findsitetype(string email);

int main()
{
    string email;
    getemail(email);
    finduser(email);
    findsitetype(email);

    system("pause");

    return 0;
}
void getemail(string &email)
{
    cout << "Please enter your email address: ";
    cin >> email;
    cout << endl;
}
void finduser(string email)
{
    int index = email.find('@');
    cout << "Username: ";
    for (int i = 0; i < index; i++)
        cout << email[i];
    cout << endl << endl;
}
void findsitetype(string email)
{
    int truesize = size(email);
    string lastthree;
    for (int i = 0; i < 3; i++)
    {
        lastthree[i] = email[truesize - i];
    }
    cout << "Site type: ";
    if (lastthree == "edu")
        cout << "Educational institutions";
    if (lastthree == "org")
        cout << "Not-for-profit organizations";
    if (lastthree == "gov")
        cout << "Government entities";
    if (lastthree == "mil")
        cout << "Military installations";
    if (lastthree == "net")
        cout << "Network service providers";
    if (lastthree == "com")
        cout << "Commercial ventures";
    if (email[truesize - 2] == '.')
        cout << "Country Code " << email[truesize - 1] << email[truesize];
}

当我运行代码时,它会吐出用户名,但在找到网站类型时似乎有致命的错误。我认为这与我不正确的字符串使用有关?任何帮助表示赞赏。

  

Debug Assertion失败!

     

程序:C:\ windows \ SYSTEM32 \ MSVCP140D.dll文件:c:\ program files   (x86)\ microsoft visual studio 14.0 \ vc \ include \ xstring Line:1681

     

表达式:字符串下标超出范围

     

有关程序如何导致断言的更多信息   失败,请参阅关于断言的Visual C ++文档。

     

(按“重试”调试应用程序)

1 个答案:

答案 0 :(得分:1)

你的代码有几个问题,(1)要获得字符串的长度,使用 length()函数,所以:

int truesize = size(email);

应该是

int truesize = email.length();

我将if语句更改为else ifs,因为如果其中一个条件语句的计算结果为true,我们就不需要检查其余的语句。

(2)您的for循环正在反向抓取电子邮件扩展名,更改:

for (int i = 0; i < 3; i++)
{
    lastthree[i] = email[truesize - i];
}

lastthree = email.substr(truesize-3, truesize);