为源文件的每一行提取和创建单独的txt文件

时间:2015-02-15 09:14:44

标签: c++

我的源文件如下:

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

我使用getline函数提取每一行并将其存储到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++;

}

此代码中的问题是,它仅限于10行,即

data1.txt,data2.txt ........ upto data9.txt已创建,然后在文本文件的名称中创建垃圾值。

我知道表达式fileName [4] =&#39; 0&#39; + x;由于我试图将整数转换为单个字符,因此最多有10个值。

有没有办法,我可以将123整数值(如果源文件中有123行)转换为&#34; 123&#34;字符串值,这样 为每一行创建123个文本文件。 (data1.txt,data2.txt ... data123.txt)

我知道在C中,我们可以使用像

这样的东西
int x = 123;

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

输出是字符串

Character value is 123

但是,我需要与c ++中的相同。

请让我知道; 谢谢,

0 个答案:

没有答案