0

I have the source file like below:

This is the details of the data
data1 | 10 20 30 40 50 60
data2 | 70 80 90 15 25 35

I'm extracting each line using getline function and storing it into textfile

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

char fileName[10] = "data "; // includes null character
char fileExt[5] = ".txt"; // includes null character

while(getline(readfile,line)){

     int x = 1;

     fileName[4] = '0'+x; // converts ineteger to character

     strcat(fileName,fileExt);


     std::ofstream outputFile( fileName );
     outputFile << line <<std::endl;

     x++;

}

The problem in this code is, it is limited to 10 lines,i.e,

data1.txt, data2.txt ........ upto data9.txt is created and then junk values are created in name of the text file.

I know that the expression fileName[4] = '0'+x; has limitations upto 10 values, as i'm trying to convert integer to a single character.

Is there any way, that i can convert say 123 integer value (if there are 123 lines in source file) to "123" character string value, so that 123 text files are created for each line. (data1.txt, data2.txt...data123.txt)

I know in C, we can use something like

int x = 123;

char c[20];
sprintf(c, "%d", n);
printf("Character value is %s", c);

The output is character string

Character value is 123

But, i need equivalent that of in c++.

Please let me know; Thanks,

  • 1
    Personally I still just use snprintf when it comes to things like this. – Kaslai Feb 15 '15 at 09:22
  • What does all that have to do with `getline()`? That said, it can't be that difficult to locate info how to convert a number to a string, it's not like it's anything unusual. – Ulrich Eckhardt Feb 15 '15 at 09:27
  • can you please care to share the knowledge on converting a number to a string..? – anil150886 Feb 15 '15 at 09:31
  • For a couple of possibilities, you could use a `std::ostringstream`, or (if your compiler isn't too old) `std::to_string`. – Jerry Coffin Feb 15 '15 at 09:33

0 Answers0