Hello.
I have got file named contacts.txt. There is a text in 4 lines with information about contact. First line is number ID of person, second number is NAME, third number is SURNAME, fourth number is PHONE NUMBER.
For example:
ID
NAME
SURNAME
PHONE_NUMBER
And I want to convert those 4 lines to 1 line with separators "|" and rewrite these contacts in other file named converted_contacts.txt
For example:
ID|NAME|SURNAME|PHONE_NUMBER|
I got something like this, it only copies contacts to other file same way.
#include <iostream>
#include <string>
#include <cstdlib>
//#include <conio.h> // <--- Not used and should not be used.
#include <fstream>
usingnamespace std;
int main()
{
int number_of_lines;
string line;
ifstream file_in("contacts.txt");
ofstream file_out("converted_contacts.txt");
if (!file_in)
{
std::cerr << "\n File \"" << "contacts.txt" << "\" did not open\n\n";
return 1;
}
if (!file_out)
{
std::cerr << "\n File \"" << "converted_contacts.txt" << "\" did not open\n\n";
return 2;
}
for (number_of_lines = 1; getline(file_in, line); number_of_lines++)
{
cout << number_of_lines << " : " << line << endl;
file_out << line << endl;
}
file_out.close(); // <--- Not required as the dtor will close the files when the function looses scope.
system("pause");
return 0;
}
Your problem is in the for loop lines 34 and 35.
You want the output of ID|NAME|SURNAME|PHONE_NUMBER| what you really want is ID|NAME|SURNAME|PHONE_NUMBER.
Line 34 replaces the (|) with (:) and 35 just outputs what you read. See a problem here.
If you want the output file to look like your example then you have to tell it to print that way.
I will need a few minutes to write the proper line and test it, but I will give you an idea of what I am thinking of.
Thank you for your fast answer Handy Andy! I'm beginner I'll take notes thanks for advices.
I want separator "|" at the end too. Like this:
ID|NAME|SURNAME|PHONE_NUMBER|
ID 2|NAME 2|SURNAME 2|PHONE_NUMBER 2|
Is it possible?