使用带有字符串类型参数的fputs

Using fputs with an argument of type string

本文关键字:类型参数 fputs 字符串      更新时间:2023-10-16

我在c++中使用fputs在文件中写入字符串。

fputs (const char*, FILE*);

如果我使用一个简单的语句,如

fputs ("information", pFile);

一切正常,"information"将被写入文件。但是如果我写一个类型为

的变量

std::vector<std::string>

插入文件,一些非ascii字符存储在文件中。我是否必须使用一种方法将类型std::vector<std::string>转换为fputs可以识别的格式?

正确的是,fputs不理解std::vector是如何在内存中布局的。

当您试图将std::vector传递给fputs()时,您实际上应该得到编译错误。您是否尝试通过添加强制转换或其他方式来解决错误?

使用

fprintf ( pFile, "%s", iterVar.at(currentRun).c_str() )

代替

fprintf ( pFile, "%s", iterVar.at(currentRun).data() )

永远不要使用data(),因为它缺少末尾的

(此代码基于提问者对@GregHewgill的回答的评论,其中iterVarvector<string>类型)