C++无法写入文件

C++ can't write to file

本文关键字:文件 C++      更新时间:2023-10-16

我已经为这段代码苦苦挣扎了一段时间了。简单地提出我的问题,我想从文件1中读取2个名称,然后将其写入文件2的行。它可以很好地读取名称,但不会将其写入 file2。

#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;
}
cout << Dni << endl;
cout << Meno << endl;
break;
}
line_num++;
}
VolneDni << Dni;
}
}

超出此条件的逻辑是什么: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;

有多个变化。您应该检查文件是否成功打开。每次都应重新生成随机数。此外,应在每次迭代时从头开始读取文件。在中断循环之前写入输出文件。

工作代码应该是:

#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
using namespace std; 
int main()
{
int rand1 = 0,line_num = 0;
string Meno,Dni;

fstream VolneDni ("C:/Programovanie/Generator_dot/Dni.txt");

for (int i = 0; i < 2; i++)
{
srand((unsigned int)time(NULL));
rand1 = rand() % 16;
fstream ZoznamMien ("C:/Programovanie/Generator_dot/Dotaznik.txt");
if( !ZoznamMien.is_open() ) {
cout<<" file did not open "<<endl;
return 0;
}
Dni="";
while (getline(ZoznamMien, Meno))
{
if (line_num == rand1)
{
getline(VolneDni, Dni);
if (i == 0)
{
Dni = Dni + ' ' + Meno + ',';
}
else
{
Dni = Dni + ' ' + Meno;
}
cout << Dni << endl;
cout << Meno << endl;
VolneDni << Dni;
break;
}
line_num++;
}
}
}