im working on a little program which should extract locations and ip-addresses from a csv, storing them in two arrays and then write them back into a config file. My code is working fine aside from the fact that i get a newline added after each ip-address. Is there a way to remove it? I tried string::erase but without success.
This is my code:
int main()
{
string use = "test";
string alias;
string hostgroup = "allhosts,switches";
char line[200];
string hostname_store[100];
string address_store[100];
int hostnameCount = 0;
int addressCount = 0;
ifstream inputfile("input.csv");
while (inputfile.getline(line, sizeof line))
{
char *token;
token = strtok(line, ";");
int counter = 1;
while (token != nullptr)
{
counter++;
if (counter % 2 == 0)
{
hostname_store[hostnameCount] = token;
hostnameCount++;
}
else
{
address_store[addressCount] = token;
addressCount++;
}
token = strtok(nullptr, ";");
}
}
for (int i = 0; i < 100; i++)
{
if (hostname_store[i] == "")
{
cout << "\n";
break;
}
cout << i << ": " << hostname_store[i] << "\n";
}
for (int i = 0; i < 100; i++)
{
address_store[i].erase(std::remove(address_store[i].begin(), address_store[i].end(), '\n'), address_store[i].cend());
if (address_store[i] == "")
{
cout << "\n";
break;
}
cout << i << ": " << address_store[i] << "\n";
}
ofstream myfile;
myfile.open("example.txt");
hostgroup = hostgroup + ",defendo_extern";
for (int i = 0; i < 100; i++)
{
if (hostname_store[i] == "")
{
break;
}
alias = hostname_store[i] + "_extern";
myfile << "define host {" << endl;
myfile << "use\t\t\t" << use << "\t\t\t\t\t\t\t\t\t; Inherit default values from a template" << endl;
myfile << "hostname\t" << hostname_store[i] << "\t\t\t\t\t\t\t\t\t; The name we're giving to this switch" << endl;
myfile << "alias\t\t" << alias << "\t\t\t\t\t\t\t; A longer name associated with the switch" << endl;
myfile << "address\t\t" << address_store[i] << "; IP address of the switch" << endl;
myfile << "hostgroups\t" << hostgroup << "\t\t\t;Host groups this switch is associated with" << endl;
myfile << "}" << endl;
myfile << "\n"
<< endl;
}
myfile.close();
}
It works fine aside from the output which is like this:
define host {
use test ; [description]
hostname example ; [description]
alias example_extern ; [description]
address 123.122.123.112
; [description]
hostgroups allhosts,switches,defendo_extern ;[description]with
}
The CSV looks like this:
example;123.123.123.123
example2;123.111.222.123
as you can see there is a inserted newline \n after the ip address. Would be awesome if anyone has a idea how to get rid of it. Thanks for your help!