问题描述
这是我在 StackOverflow 上的第一个问题,所以如果我的问题中遗漏了任何内容或我没有遵循的某些规则,我会提前道歉。请编辑我的问题或在评论中告诉我我应该如何改进我的问题,谢谢。
我正在尝试使用 std::vector<unsigned char>
将二进制文件读入 C++ 中的 std::ifstream
。问题是文件读取成功,但向量仍然为空。
void readFile(const std::string &fileName,std::vector<unsigned char> &fileContent)
{
std::ifstream in(fileName,std::ifstream::binary);
// reserve capacity
in.seekg(0,std::ios::end);
fileContent.reserve(in.tellg());
in.clear();
in.seekg(0,std::ios::beg);
// read into vector
in.read(reinterpret_cast<char *>(fileContent.data()),fileContent.capacity());
if(in)
std::cout << "all content read successfully: " << in.gcount() << std::endl;
else
std::cout << "error: only " << in.gcount() << " Could be read" << std::endl;
in.close();
}
std::vector<unsigned char> buf;
readFile("file.dat",buf);
std::cout << "buf size: " << buf.size() << std::endl;
all content read successfully: 323
buf size: 0
当我尝试像这样打印矢量中的项目时:
for(const auto &i : buf)
{
std::cout << std::hex << (int)i;
}
std::cout << std::dec << std::endl;
我得到空输出。
我检查过的东西
-
file.dat
与程序在同一目录中 -
file.dat
不为空
那么,我做错了什么吗?为什么读后向量为空?
解决方法
import npyscreen,pymysql,time
class MyTestApp(npyscreen.NPSAppManaged):
def onStart(self):
self.registerForm("MAIN",MainForm())
class MainForm(npyscreen.Form):
def create(self):
while True:
con = pymysql.connect(host='',user='',password='',database='')
cur = con.cursor()
cur.execute(f"SELECT COUNT(Id) FROM Log")
t = cur.fetchone()[0]
print(t)
time.sleep(1)
self.add(npyscreen.TitleText,name="Text:",value=str(t))
def afterEditing(self):
self.parentApp.setNextForm(None)
if __name__ == '__main__':
TA = MyTestApp()
TA.run()
分配内存,但不会将分配的区域注册为有效元素。
您应该使用 struct MainListView: View {
@ObservedObject var model: Model
var body: some View {
List {
ForEach(model.mainItems) { model in
MainView(model: model)
}
}
}
}
添加元素并使用 reserve()
计算元素。
resize()