我无法找到任何明显的答案,而且我很难过。
当我想将变量字符串写入文本文档时,我需要做一些不同的事情,而当我想在所述文档中只写一个字符串时,我需要做什么?
此代码将正确写入" set string"在newfile.txt上的8个单独行上(并创建它)。
string output_file = "newfile.txt"
ofstream file_object_2;
file_object_2.open(output_file, std::ofstream::out | std::ofstream::app);
string nextline;
for (int i = 0; i <= row_number; ++i)
{
file_object_2 << "set string" << "\n";
}
file_object_2.close();
return 0;
但这会使文件完全为空,即使line_vector [i]本身也有字符串(并且cout可以打印它们)
string output_file = "newfile.txt"
ofstream file_object_2;
file_object_2.open(output_file, std::ofstream::out | std::ofstream::app);
string nextline;
for (int i = 0; i <= row_number; ++i)
{
nextline = line_vector[i];
file_object_2 << nextline << "\n";
}
file_object_2.close();
return 0;
我试着查看文档,并按照他们的方式完成,但我在这里没有成功。显然是因为我自己的失败,但我无法弄清楚我在哪里错了。
与这两个代码的唯一区别在于我试图写入文档的行
file_object_2 << nextline << "\n";
vs
file_object_2 << "set string" << "\n";
main(),我试图减少它,因此它具有较少的动态功能(没有手动输入)但仍然不起作用:
文本文件&#34; a.txt&#34;只有几行随机字符串
[a.txt]
("Yogi has a best friend too
Boo Boo, Boo Boo
Yogi has a best friend too
Boo Boo, Boo Boo Bear
Boo Boo, Boo Boo Bear
Boo Boo, Boo Boo Bear
Yogi has a best friend too
Boo Boo, Boo Boo Bear")
功能本身
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main() {
string input_file = "a.txt";
vector<string> line_vector;
string output_file = "output.txt";
// reads from the original text file. Included in the example because I might
// be constructing the vector in a stupid way and this is where it happens
int row_number = 0;
string line;
while (getline(file_object, line) )
{
cout << line << endl;
line_vector.push_back(line);
++row_number;
}
file_object.close();
// writing onto a new file starts, this is where I'd assume the problem is
ofstream file_object_2;
file_object_2.open(output_file, std::ofstream::out | std::ofstream::app);
string nextline;
for (int i = 0; i <= row_number; ++i)
{
nextline = i + " " + line_vector[i];
file_object_2 << nextline << "\n";
}
file_object_2.close();
return 0;
}
答案 0 :(得分:1)
这是破碎的:
i + " " + line_vector[i]
您的意思是to_string(i) + " " + line_vector[i]
,但您直接在+
和i
上使用了""
,编译器确定它是operator+(int, const char*)
,它是指针算术,而不是将i
转换为字符串。由于所讨论的字符串只有一个字符(NUL),因此添加1
数字会导致无法解除引用的过去结束指针,添加更大的数字已经是未定义的行为。
最简单的解决方法是将i
与nextline
分开,然后直接将其写入文件。你的循环体变成:
{
nextline = line_vector[i];
file_object_2 << i << " " << nextline << "\n";
}
但它也可以使用i
将std::to_string()
转换为字符串。
作为旁注,您声明的第一段代码已被破坏(其中nextline = line_vector[i];
)实际上很好。如果你打算测试你可能自己发现了问题。