英文:
Failed to open json file
问题
以下是您要翻译的部分:
我需要加载一个JSON文件并将其复制到一个字符串缓冲区,但是打开文件失败了。可能的问题是什么,我可以使用其他方法吗?
我的JSON文件如下:
{
"ip": [ "212.253.144.10","192.32.12.1","192.12.1.1"]
}
以及代码:
#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
void CMFCJasonDlg::OnBnClickedButton2()
{
ifstream inputFile("C:\\Users\\hp\\Desktop\\VK\\ip.json");
if (!inputFile.is_open())
{
MessageBox(L"Failed to open file", 0, 0);
CloseHandle(hdevice);
return;
}
stringstream buffer;
buffer << inputFile.rdbuf();
string inputString = buffer.str();
inputFile.close();
DWORD inputBufferSize = sizeof(inputString);
char* inputBuffer = new char[inputBufferSize];
strncpy_s(inputBuffer, inputBufferSize, inputString.c_str(), inputString.size());
delete[] inputBuffer;
}
英文:
I need to load a JSON file and copy it into a string buffer but it is failing to open the file.
What could be the problem, can I use any other method?
My JSON file is as follows:
{
"ip": [ "212.253.144.10","192.32.12.1","192.12.1.1"]
}
and the code:
#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
void CMFCJasonDlg::OnBnClickedButton2()
{
ifstream inputFile("C:\\Users\\hp\\Desktop\\VK\\ip.json");
if (!inputFile.is_open())
{
MessageBox(L"Failed to open file", 0, 0);
CloseHandle(hdevice);
return;
}
stringstream buffer;
buffer << inputFile.rdbuf();
string inputString = buffer.str();
inputFile.close();
DWORD inputBufferSize = sizeof(inputString);
char* inputBuffer = new char[inputBufferSize];
strncpy_s(inputBuffer, inputBufferSize, inputString.c_str(), inputString.size());
delete[] inputBuffer;
}
答案1
得分: 1
尝试使用
int inputBufferSize = inputString.size() + 1;
+1 用于空终止符。
英文:
Try it with
int inputBufferSize = inputString.size() + 1;
The +1 is for the null terminator
答案2
得分: 0
你的代码存在两个问题:
首先,sizeof(inputString)
返回的是变量 inputString
的大小,与其长度无关。你应该使用 inputString.length()
来获取长度。
其次,存储在字节数组中的每个字符串都以空终止符 (\0
) 结尾,你应该为它分配空间。具体来说,将 char* inputBuffer = new char[inputBufferSize];
替换为 char* inputBuffer = new char[inputBufferSize+1];
。
英文:
Your code has two problem:
First, sizeof(inputString)
returns the size of the variable inputString
, which has nothing to do with its length. You should use inputString.length()
to obtain the length.
Second, every string stored in a byte array is terminated by a null terminator (\0
) at the end, and you should allocate space for it. Specifically, replace char* inputBuffer = new char[inputBufferSize];
with char* inputBuffer = new char[inputBufferSize+1];
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论