我正在尝试创建一个cpp程序,该程序将从URL读取远程文件,例如,http://10.10.10.10/file.txt 文件包含以下格式的单词“word1”,“word2”,“word3” 我必须将文件内容按原样存储到数组“const char* Wordslist[3]={"word1","word2","word3"}"。
#include <iostream>
#include <string>
#include <vector>
#include <Windows.h>
#include <wininet.h>
#pragma comment(lib, "wininet.lib")
// Function to parse the input string and populate the wordlist array
void parseAndPopulate(const std::string& input, const char** wordlist, int size) {
std::vector<std::string> words;
size_t pos = 0;
while ((pos = input.find("\",\"", pos)) != std::string::npos) {
words.push_back(input.substr(1, pos - 1)); // Extract word between quotes
pos += 3; // Move past the ", delimiter
}
// Add the last word (no ", delimiter at the end)
words.push_back(input.substr(pos + 2, input.size() - pos - 3));
// Check if the size matches
if (words.size() != size) {
std::cerr << "Error: Number of words in the file does not match the specified size\n";
return;
}
// Copy words to wordlist array
for (int i = 0; i < size; ++i) {
wordlist[i] = words[i].c_str();
}
}
int main() {
const int size = 3; // Size of wordlist array
const char* wordlist[size]; //This does not work!!!!!!
// URL to fetch data from
const char* url = "10.10.10.10/file.txt";
HINTERNET hInternet = InternetOpenA("HTTPGET", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if (hInternet != NULL) {
HINTERNET hUrlFile = InternetOpenUrlA(hInternet, url, NULL, 0, INTERNET_FLAG_RELOAD, 0);
if (hUrlFile != NULL) {
std::string readBuffer;
char buffer[1024];
DWORD bytesRead = 0;
while (InternetReadFile(hUrlFile, buffer, sizeof(buffer), &bytesRead) && bytesRead > 0) {
readBuffer.append(buffer, bytesRead);
}
// Close the URL file handle
InternetCloseHandle(hUrlFile);
// Parse the fetched data and populate the wordlist array
parseAndPopulate(readBuffer, wordlist, size);
// Print the populated wordlist array
for (int i = 0; i < size; ++i) {
std::cout << wordlist[i] << std::endl;
}
}
else {
std::cerr << "Error: Failed to open URL " << url << std::endl;
}
// Close the internet handle
InternetCloseHandle(hInternet);
}
else {
std::cerr << "Error: Failed to initialize WinINet" << std::endl;
}
return 0;
}
如何实现这一点? 我需要“const char* wordlist[];”看起来像这样: const char* wordlist[3]={"word1","word2","word3"};
您必须将
const char* wordlist[size];
更改为 char* wordlist[size];
,因为您稍后会更改 char*。您还必须将参数 const char** wordlist
更改为 char* wordlist[]
。
在 parseAndPopulate(...) 的 for 循环中,您必须将代码更改为
wordlist[i] = (char*)malloc(sizeof(words[i].c_str()));
strcpy(wordlist[i], words[i].c_str());
malloc 分配 c_str 所需的内存并返回指向该内存的指针。
strcpy将c_str从words[i]复制到分配的内存。