C++ Semicolon separated file reading - c++

I basically have a semicolon separated text file, in that file there are some commands like "A", "P", "R", "S", and the inputs to process according to those commands like names "Ali Aksu, Mithat Köse", like transactions "Process, withdraw". I have a program which process those inputs without any problems in console (User gives the inputs). But i need to make it getting the inputs from the semicolon separated file. Here is a test for the reading:
This is an example input file:
A;Ali;Aksu;N;2;deposit;withdraw
P
A;Mithat;Köse;P;3;deposit;credit;withdraw
This is the output on the console:
A/Ali/Aksu/N/2/deposit/withdraw
P
A/Mithat/Köse/P/3/deposit/credit/withdraw
/
1.Problem: It cannot read the special characters like "ö"
2.Problem: Why is that starting with this weird "" character?
#include <iostream>
#include <fstream>
using namespace std;
int main(){
setlocale(LC_ALL, "Turkish");
fstream myfile;
char *string;
string = new char[50];
myfile.open("input_file.txt",ios::in);
while(!myfile.eof()){
myfile.getline(string, 49, ';');
cout << string << "/";
}
myfile.close();
cout << endl;
system("pause");
return 0;
}

I will assume that the file is in UTF8 format. If so then you question is really, how to i read UTF8 files using c++
here is somebody reading chinese How to read an UTF-8 encoded file containing Chinese characters and output them correctly on console?. You should be able to adapt this to your locale

Related

C++ write utf-8 to text file

How to write characters in UTF-8 coding page into text file in С++?
#include <fstream>
using namespace std;
int main() {
ofstream fout("tree.txt");
fout << "┌───────────────22───────┐" << endl;
fout.close();
return 0;
}
Wrong characters will be written into file.
If you want to write UTF-8 literals, then you should encode the source file with UTF-8, and make sure that the compiler reads the input as UTF-8. If you've done that, then the output should be correct. You could use u8"┌───────────────22───────┐" literal just to be sure. Unfortunately, there's no std::basic_ifstream<char8_t> though.

New line seen in command prompt but the same string is seen with \n in file output

I have this code which runs fine
#include <iostream>
#include <set>
#include <sstream>
int main()
{
std::set<std::string> a;
a.insert("foo");
a.insert("bar");
a.insert("zoo");
a.insert("should");
a.insert("work");
std::stringstream b;
std::set<std::string>::iterator it;
for (it = a.begin(); it != a.end(); it++)
{
b << " " << *it <<"," <<"\n";
}
std::string aaa = b.str();
std::cout <<aaa;
}
Output in command prompt:
bar, //new line after ","
foo, //new line after ","
should,
work,
zoo,
If I try to write the same string aaa in file I am expecting the same output to get print in the file i.e. every string after "," in new line, rather I am getting output in my file as follows (In single line with \n):
" bar,\n foo,\n should,\n work,\n zoo,\n"
Can anyone help me with this?
More Information on writing the string in file:
Here's how I am writing into file:
boost::property_tree::ptree pt1;
pt1.put( "Output", aaa );
boost::property_tree::write_json( "result.json", pt1 );
This will write JSON file, output of the above code in (Windows - NotePad/NotePad++) is as below:
{
"Output": " bar,\n foo,\n should,\n work,\n zoo,\n"
}
You are not writing a normal file! You are using a JSON library to write a file for you. And as it happens, in JSON strings, the end-of-line character is escaped just like in C source files, that is as "\n".
So, summing up, that is the expected behavior. If you want to get normal end-of-line characters, write a normal file, with fopen() and friends.
This is expected behaviour.
You are passing the string (which contains newlines) to a JSON library for encoding into JSON. That encoding step includes converting newlines to the substring "\n", because that's how we represent newlines inside strings in JSON.
Read more about JSON on the json.org website.

c++ reading file with \ inside the text

I need help with a small problem.
I wrote a small program that reads every line of the text inside a .rd file to a string. But inside the text are some \ and when I output the strings the program think that the \ are escape characters.
What can I do to get the original text?
The Program run without an error.
Here is a small snippet of my code:
string find="something";
string replace="something2";
string line="";
fstream myfile;
myfile.open ("file.rb");
if (myfile.is_open())
{
while (getline(myfile,line))
{
cout << line << '\n';
if(line == find)
{
myfile << replace;
}
else
{
myfile << line;
}
}
myfile.close();
}
You should try using a unicode version of getline or you could try adding ios::binary to your stream constructor flags.
See this article for further info.
However, if you read in a string like "\0" from stdin or a file, it should be treated as two separate characters: '\' and '0'. There is no additional processing that you have to do.
Escaping characters is only used for string/character literals. That is to say, when you want to hard-code something into your source code.

How Read Urdu text file and then write it to other file in c++

I want to input a file containing Urdu words and write them in other file. The problem I'm facing is that Urdu language doesn't have spaces, so other file written would look alike all words joined to each other. How can i separate words or detect spaces ? My Code is this.
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
ifstream file;
ofstream myfile;
file.open ("urduwords.txt"); //File containing Urdu words
myfile.open("urduoutput.txt"); // Output file
if (!file.is_open()) return;
char * word= new char[];
while(file>>word)
{
myfile<<word;
// What to write here to separate words or detect spaces. Input file is saved in UTF-8
}
myfile.close();
file.close();
cout<<"Check output"<<endl;
}
Oh I got answer. The answer is you have to put spaces between Urdu characters because Urdu language has Space Omission Problem so at while loop
while(file>>word)
{
myfile<<word;
myfile<<" "; // Put spaces between words.
}

What's the correct way to read a text file in C++?

I need to make a program in C++ that must read and write text files line by line with an specific format, but the problem is that in my PC I work in Windows, and in College they have Linux and I am having problems because of line endings are different in these OS.
I am new to C++ and don't know could I make my program able read the files no matter if they were written in Linux or Windows. Can anybody give me some hints? thanks!
The input is like this:
James White 34 45.5 10 black
Miguel Chavez 29 48.7 9 red
David McGuire 31 45.8 10 blue
Each line being a record of a struct of 6 variables.
Using the std::getline overload without the last (i.e. delimiter) parameter should take care of the end-of-line conversions automatically:
std::ifstream in("TheFile.txt");
std::string line;
while (std::getline(in, line)) {
// Do something with 'line'.
}
Here's a simple way to strip string of an extra "\r":
std::ifstream in("TheFile.txt");
std::string line;
std::getline(input, line));
if (line[line.size() - 1] == '\r')
line.resize(line.size() - 1);
If you can already read the files, just check for all of the newline characters like "\n" and "\r". I'm pretty sure that linux uses "\r\n" as the newline character.
You can read this page: http://en.wikipedia.org/wiki/Newline
and here is a list of all the ascii codes including the newline characters:
http://www.asciitable.com/
Edit: Linux uses "\n", Windows uses "\r\n", Mac uses "\r". Thanks to Seth Carnegie
Since the result will be CR LF, I would add something like the following to consume the extras if they exist. So once your have read you record call this before trying to read the next.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
If you know the number of values you are going to read for each record you could simply use the ">>" method. For example:
fstream f("input.txt" std::ios::in);
string tempStr;
double tempVal;
for (number of records) {
// read the first name
f >> tempStr;
// read the last name
f >> tempStr;
// read the number
f >> tempVal;
// and so on.
}
Shouldn't that suffice ?
Hi I will give you the answer in stages. Please go trough in order to understand the code.
Stage 1: Design our program:
Our program based on the requirements should...:
...include a definition of a data type that would hold the data. i.e. our
structure of 6 variables.
...provide user interaction i.e. the user should be able to
provide the program, the file name and its location.
...be able to
open the chosen file.
...be able to read the file data and
write/save them into our structure.
...be able to close the file
after the data is read.
...be able to print out of the saved data.
Usually you should split your code into functions representing the above.
Stage 2: Create an array of the chosen structure to hold the data
...
#define MAX 10
...
strPersonData sTextData[MAX];
...
Stage 3: Enable user to give in both the file location and its name:
.......
string sFileName;
cout << "Enter a file name: ";
getline(cin,sFileName);
ifstream inFile(sFileName.c_str(),ios::in);
.....
->Note 1 for stage 3. The accepted format provided then by the user should be:
c:\\SomeFolder\\someTextFile.txt
We use two \ backslashes instead of one \, because we wish it to be treated as literal backslash.
->Note 2 for stage 3. We use ifstream i.e. input file stream because we want to read data from file. This
is expecting the file name as c-type string instead of a c++ string. For this reason we use:
..sFileName.c_str()..
Stage 4: Read all data of the chosen file:
...
while (!inFile.eof()) { //we loop while there is still data in the file to read
...
}
...
So finally the code is as follows:
#include <iostream>
#include <fstream>
#include <cstring>
#define MAX 10
using namespace std;
int main()
{
string sFileName;
struct strPersonData {
char c1stName[25];
char c2ndName[30];
int iAge;
double dSomeData1; //i had no idea what the next 2 numbers represent in your code :D
int iSomeDate2;
char cColor[20]; //i dont remember the lenghts of the different colors.. :D
};
strPersonData sTextData[MAX];
cout << "Enter a file name: ";
getline(cin,sFileName);
ifstream inFile(sFileName.c_str(),ios::in);
int i=0;
while (!inFile.eof()) { //loop while there is still data in the file
inFile >>sTextData[i].c1stName>>sTextData[i].c2ndName>>sTextData[i].iAge
>>sTextData[i].dSomeData1>>sTextData[i].iSomeDate2>>sTextData[i].cColor;
++i;
}
inFile.close();
cout << "Reading the file finished. See it yourself: \n"<< endl;
for (int j=0;j<i;j++) {
cout<<sTextData[j].c1stName<<"\t"<<sTextData[j].c2ndName
<<"\t"<<sTextData[j].iAge<<"\t"<<sTextData[j].dSomeData1
<<"\t"<<sTextData[j].iSomeDate2<<"\t"<<sTextData[j].cColor<<endl;
}
return 0;
}
I am going to give you some exercises now :D :D
1) In the last loop:
for (int j=0;j<i;j++) {
cout<<sTextData[j].c1stName<<"\t"<<sTextData[j].c2ndName
<<"\t"<<sTextData[j].iAge<<"\t"<<sTextData[j].dSomeData1
<<"\t"<<sTextData[j].iSomeDate2<<"\t"<<sTextData[j].cColor<<endl;}
Why do I use variable i instead of lets say MAX???
2) Could u change the program based on stage 1 on sth like:
int main(){
function1()
function2()
...
functionX()
...return 0;
}
I hope i helped...