C++无法写入文件
C++ can't write to file
我已经为这段代码苦苦挣扎了一段时间了。简单地提出我的问题,我想从文件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++;
}
}
}
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到