我有一个函数,应该从参数中给出的字符串下载一个网站(exacly string是url的结尾)。它让我失败
变量'url'周围的堆栈已损坏。
我的代码:
void download_wordnik(string word) {
string s1 = word;
std::wstring w_word_Tmp1(s1.begin(), s1.end());
wstring w_word1 = w_word_Tmp1;
std::wstring stemp1 = std::wstring(s1.begin(), s1.end());
LPCWSTR sw1 = stemp1.c_str();
TCHAR url[] = TEXT("https://www.wordnik.com/words");
wsprintf(url, TEXT("%s\/%s\/"), url, sw1);
LPCWSTR sw2 = stemp1.c_str();
TCHAR path[MAX_PATH];
GetCurrentDirectory(MAX_PATH, path);
wsprintf(path, TEXT("%s\\wordnik\\%s\.txt"), path, sw2);
HRESULT res = URLDownloadToFile(NULL, url, path, 0, NULL);
// Checking download
if(res == S_OK) {
printf("Ok\n");
} else if(res == E_OUTOFMEMORY) {
printf("Buffer length invalid, or insufficient memory\n");
} else if(res == INET_E_DOWNLOAD_FAILURE) {
printf("URL is invalid\n");
} else {
printf("Other error: %d\n", res);
}
}
我正在使用此包含
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <Urlmon.h>
#include <regex>
#pragma comment(lib, "urlmon.lib")
using namespace std;
答案 0 :(得分:4)
可能是因为您复制url
超过其容量而导致未定义的行为:
TCHAR url[] = TEXT("https://www.wordnik.com/words");// The size is `30` but ...
wsprintf(url, TEXT("%s\/%s\/"), url, sw1);// It copies more than `30` characters.
使用std::wstring
方法,不要弄乱xprintf
方法和固定大小的数组。我不熟悉TCHAR
或TEXT
(Windows事物),但您可以这样做:
std::wstring url;
url = std::wstring(TEXT("https://www.wordnik.com/words/")) + sw1 + TEXT("/");
答案 1 :(得分:0)
当您url
进入wsprintf
时,您正在std::wostringstream urlstream;
urlstream << TEXT("https://www.wordnik.com/words/") << sw1 << TEXT("/");
std::wstring url = urlstream.str();
范围之外写作。
而是(用于一般格式化)
std::wstring url = std::wstring(TEXT("https://www.wordnik.com/words/")) + sw1 + TEXT("/");
或(更简单)
std::wstring w_word(word.begin(), word.end());
std::wstring url = std::wstring(TEXT("https://www.wordnik.com/words/")) + w_word + TEXT("/");
TCHAR currentpath[MAX_PATH];
GetCurrentDirectory(MAX_PATH, currentpath);
std::wstring path = std::wstring(currentpath) + TEXT("\\wordnik\\") + w_word + TEXT(".txt");
HRESULT res = URLDownloadToFile(NULL, url.c_str(), path.c_str(), 0, NULL);
你正在复制很多变量 - 据我所知,你可以将代码缩减到这个:
{{1}}