c++ array error while executing

时间:2015-10-30 22:13:51

标签: c++

When i run my program i keep getting this error. The program will still execute and run and display the correct nymbers in the terminal, but I need it to ouput another file and put them on there. please help new to c++.

bash-3.2$ g++ -Wall 1.cpp
1.cpp: In function 'std::string IP_Calculation(std::string*, std::string, int)':1.cpp:71:1: warning: control reaches end of non-void function [-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";
    }
}

2 个答案:

答案 0 :(得分:1)

The warning is because the function is declared to return a string, but the compiler has determined that it's possible that it may not do that. You have a return statement that returns a string in your if statement. But when Total_IPs is 0, you won't execute that block of code, and you'll never execute that return statement. Since you don't have an else block, you'll just exit the function, without returning a string as required. You need to change it to:

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

so that you return something when the condition fails.

答案 1 :(得分:-2)

I'm not sure if I understand. You want to write the output in a file? Something like this should work:

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