使用此代码,我尝试以二进制格式打印字符串"foo"10次.但为什么这个功能没有起作用呢?
#include <iostream>
#include <fstream>
using namespace std;
template <typename T> void WriteStr2BinFh (string St, ostream &fn) {
for (unsigned i = 0; i < St.size(); i++) {
char CStr = St[i];
fn.write(&CStr.front(), CStr.size());
}
return;
}
int main() {
string MyStr = "Foo";
ofstream myfile;
myfile.open("OuputFile.txt", ios::binary|ios::out);
// We want to print it 10 times horizontally
// separated with tab
for (int i = 0; i < 9; i++) {
WriteStr2BinFh(Mystr+"\t", myfile);
}
myfile.close();
}
Run Code Online (Sandbox Code Playgroud)
这里有很多错误,我只想列出我看到的一切:
你的for循环条件应该是<10.
你为什么使用模板而不是模板化的参数T?
你在CStr上调用方法front(),但CStr是一个char,而不是一个字符串,所以我甚至不知道如何编译.
假设CStr是一个字符串,你不想使用&获取front()迭代器的地址,而是想要说出如下内容:
fn.write(St.c_str(), St.size());
Run Code Online (Sandbox Code Playgroud)
并且您不希望为St.size()迭代循环.只要做上面的事情.
| 归档时间: |
|
| 查看次数: |
14023 次 |
| 最近记录: |