我在这段代码中苦苦挣扎了一段时间。简单地说,我想从file1读取2个名称,然后将其写入file2的行。它可以读取名称,但不会将其写入文件2。
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
int main()
{
int rand1 = 0,line_num = 0;
string Meno,Dni;
fstream ZoznamMien ("C:/Programovanie/Generator_dot/Dotaznik.txt");
fstream VolneDni ("C:/Programovanie/Generator_dot/Dni.txt");
srand((unsigned int)time(NULL));
rand1 = rand() % 16;
for (int i = 0; i < 2; i++)
{
while (getline(ZoznamMien, Meno))
{
if (line_num == rand1)
{
getline(VolneDni, Dni);
if (i == 0)
{
Dni = Dni + ' ' + Meno + ',';
}
else
{
Dni = Dni + ' ' + Meno;
VolneDni << Dni;
}
cout << Dni << endl;
cout << Meno << endl;
break;
}
line_num++;
}
}
}
超出此条件的逻辑是什么:if (line_num == rand1)
。
它基于随机数,因此只有在此rand1
在第一次迭代中仅值为0,在第二次迭代中为1或在第三次迭代中为2时,才会写入file2。
让我们看一下在其中创建新字符串并将其写入文件的代码(并添加一些注释):
if (i == 0)
{
// Create the new string
Dni = Dni + ' ' + Meno + ',';
// Don't write the new string to the file
}
else
{
// Create the new string
Dni = Dni + ' ' + Meno;
// Write the new string to the file
VolneDni << Dni;
}
您仅写入else
部分中的字符串,而不是写入i == 0
时。
一种解决方法是在if
之后写之后]:
// Create the new string
if (i == 0)
{
Dni = Dni + ' ' + Meno + ',';
}
else
{
Dni = Dni + ' ' + Meno;
}
// Write the new string to the file
VolneDni << Dni;