执行时出现c++数组错误

c++ array error while executing

本文关键字:数组 错误 c++ 执行      更新时间:2023-10-16

当我运行程序时,我不断收到这个错误。该程序仍将执行和运行,并在终端中显示正确的名称,但我需要它来输出另一个文件并将它们放在那里。请帮助刚接触c++的人。

bash-3.2$g++-Wall 1.cpp
1.cpp:在函数"std::string IP_Calculation(std::string*,std::字符串,int)"中:1.cpp:71:1:警告:控件到达非无效函数[-Wreturn type]的末尾


string IP_Calculation(string IP[], string Company_name, int total_IPS)
{
    string temp = "";
    char buf[80];
    char buf2[80];
    if (total_IPS != 0)
    {
        int UniqueIP_count = total_IPS;
        for (int i = 0; i < total_IPS; i++)
        {
            for (int j = i + 1; j < total_IPS; j++)
            {
                if (strcmp(IP[i].c_str(), IP[j].c_str()) == 0)
                {
                    if (strcmp(IP[i].c_str(), "") == 0)
                    {
                        continue;
                    }
                    IP[j] = "";
                    UniqueIP_count--;
                }
            }
        }
        temp = print_array(IP);
        cout << Company_name << " | Number of Visitor: " << total_IPS
                << "| Unique         Visitors: " << UniqueIP_count << endl;
        //cout<<Company_name<<" | Number of Visitor: "<<buf <<"| Unique  Visitors:      "<<UniqueIP_count<<endl;
        cout << temp;
        sprintf(buf, "%d", total_IPS);
        sprintf(buf2, "%d", UniqueIP_count);
        // return temp=Company_name+" | Number of Visitor: "+( total_IPS) +"|      Unique   Visitors: "+to_string( UniqueIP_count)+"n"+temp+"n";
        return temp = Company_name + " | Number of Visitor: " + buf
                + "| Unique   Visitors:   " + buf2 + "n" + temp + "n";
    }
}

警告是因为函数被声明为返回string,但编译器已经确定它可能不会这样做。您有一个return语句,它在if语句中返回一个字符串。但是当Total_IPs0时,您将不会执行该代码块,也永远不会执行return语句。由于没有else块,您只需退出函数,而不需要根据需要返回字符串。您需要将其更改为:

if (Total_IPs != 0) {
    ...
} else {
    return "";
}

以便在条件失败时返回一些内容。

我不确定我是否理解。您想将输出写入文件中吗?像这样的东西应该起作用:

int writeFile () 
{
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.n";
  myfile.close();
  return 0;
}