0

My input file stored in the txt format is some thing like:

data1 : 15 16 20 23 56
data2 : 15 65 89 64 65

so, I'm extracting the each line into string format into a separate files like below

Macro definition:

    #define STRINGIFY_INIT(x)  #x
    #define STRINGIFY(x)  STRINGIFY_INIT(x)

    #define FILE_PREFIX   data
    #define FILE_EXT      .txt

    #define CONCAT_FILE(a) STRINGIFY(FILE_PREFIX) STRINGIFY(a) STRINGIFY(FILE_EXT)

Code Starts something like this:

    std::string line;

    std::ifstream readfile;
    readfile.open("read.txt");

    while(getline(readfile,line)){
      int x = 1;
      std::ofstream outputFile( CONCAT_FILE(x) );
      outputFile << line <<std::endl;
      std::cout<<line<<std::endl;
      x++;
    }

Now, this code creates the file called "datax.txt" and in the text file, it is the last extracted data from the inputfile is present.i.e,

data2 : 15 65 89 64 65

But, my requirement is it to create 2 files with name data1.txt and data2.txt, as there 2 lines of data present in the original input file.

The problem, I'm having is in the line:

    std::ofstream outputFile( CONCAT_FILE(x) );

the expression "CONCAT_FILE(x) ", is not taking the value of x, but it is simply taking ASCII character "x".So, a single file with the name "datax.txt" is created and not "data1.txt","data2.txt".

I expected to work like, CONCAT_FILE(1) for the first iteration and CONCAT_FILE(2) for the next iteration, so that 2 files "data1.txt","data2.txt" are created.

Could any one please help me out.

I need to create 2 separate files, so that i can read only integer values separately and want to calculate mean for each of them.

Please do the needfull. Thanks,

  • Why have you tagged this as C? – Ulrich Eckhardt Feb 14 '15 at 18:08
  • well, the problem is with the macro expression, 'CONCAT_FILE(x)', which i'm trying to get the number (value of x) to be attached to file name. Macro's, I guess it would be same both in c and c++. – anil150886 Feb 14 '15 at 18:13
  • You need a way to convert the integer to a string for use as filename, which should be trivial to find solutions for. The preprocessor is a mere text replacement tool, it doesn't even know about types like `int` or `float`. – Ulrich Eckhardt Feb 14 '15 at 18:14
  • I expected to work like, CONCAT_FILE(1) for the first iteration and CONCAT_FILE(2) for the next iteration, so that 2 files "data1.txt","data2.txt" are created. – anil150886 Feb 14 '15 at 18:26
  • Get rid of all those macros and use [proper C++ string manipulation functions](http://stackoverflow.com/q/4983092/1392132). Then your code will work. Macros are for compile-time text substitution – they cannot use the value of a variable at run-time. – 5gon12eder Feb 14 '15 at 18:30

0 Answers0