Saturday, May 22, 2010

How to write c++ code to read comma deliminated text files and give out put as a textfile with comma delimnate

i have a c++ program which takes about 10 textfiles as input to read data in the textfile and after calculation gives out another 6 textfiles with single data in each text file


i want to modify the c++ program and want to give single textfile with 10 values separated by comma (,) and similarly one output texfile


any body can help me out how to read comma (,) deliminater in c or c++ (the values are both string and integers)

How to write c++ code to read comma deliminated text files and give out put as a textfile with comma delimnate
You don't even have to keep track of comma deliminated variables in your input file, unless the files include strings which themselves include commas.





You can handle files two ways: either with the traditional cstdio syntax:





Infile = fopen("data.txt", "r");





or with the fstream library:





fstream Infile("data.txt", ios::in);





In the former case, an fscanf(Infile, "%d", %26amp;variable); (you do need to specify the type of the variable), will read up to the comma because it is a whitespace character, convert it (to int here) and stores it in variable. In the latter case, you mostly don't need to worry: Infile %26gt;%26gt; variable; will do the same thing.





For output, you would do an fprintf(Outfile, "%d, ", variable); --- that is, the conversion type, a comma, a space and a close quote, and for an ofstream it would be Outfile %26lt;%26lt; variable %26lt;%26lt; ", "; again, the variable, followed immediately by the comma and space.





Aside from just being aware of what your variables are, both methods have slight problems with ASCIIZ strings. ; They don't read white spaces. If you have a text file with the phrase: "This is the Modern World" and do an fscanf(Infile, "%s", %26amp;variable);, an printf("%s.",variable); will reveal "This". Obviously you would have to use fread or getline in the old syntax, and c=Infile.get() or some other way to get unformatted data in the new. But if you keep track of the variables the commas will take care of themselves.


No comments:

Post a Comment