str轉wstr的三種方法和從網站獲取json數據到數據隨機提取,返回拼接字符串和動態數組

庫的設置 hv庫
外部包含目錄:…\include\libhv_new\hv;
庫目錄:…\include\libhv_new\lib\x86\Release;
附加依賴項:hv.lib;

//Get請求 獲取json數據,然后提取符合 條件的,time值大于自定義變量的值,然后取出來,再抽取自定義個數,比如3個,把name拼接返回,再把數據放進動態數組也返回,兩種類型的返回!23-11-21#include "requests.h"
#include <unordered_set> 
struct DataItem {int id;std::wstring name;bool isChange;
};
using Json = nlohmann::json;
std::vector<DataItem> dataItems;struct ServerDataResult {std::wstring concatenatedNames;std::vector<DataItem> dataItems;
};
//--------------str 轉 wstr 的三種方法 -----------------
std::wstring convertToWideString1(const std::string& str) {std::wstring wideStr(str.begin(), str.end());return wideStr;//構造函數 更簡潔
}
std::wstring convertToWideString2(const std::string& str) {std::wstring wideStr;wideStr.resize(str.size(), L' ');std::copy(str.begin(), str.end(), wideStr.begin());return wideStr;
}
//-----------------第三種通用,但需要頭文件--------------------------
#include <locale>
#include <codecvt>
/*
這種方法使用了 std::wstring_convert 類模板和 std::codecvt_utf8 類模板,它們提供了跨平臺的支持,能夠在不同的字符編碼環境中進行字符串轉換。
這里的示例使用了 UTF-8 編碼,你可以根據需要選擇其他字符編碼,如 UTF-16 或 UTF-32。
這種方法的優點是它是標準庫提供的通用解決方案,不依賴于特定的平臺或編譯器。它能夠在不同的機器和代碼之間保持一致,并且適用于大多數常見的字符編碼方案。
*/
std::wstring convertToWideString3(const std::string& str) {std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;return converter.from_bytes(str);
}std::string convertToNarrowString(const std::wstring& wstr) {std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;return converter.to_bytes(wstr);
}
//==========================================================================================std::pair<std::wstring, std::vector<DataItem>> GetServerData(int numNamesToExtract, int times) {std::wstring concatenatedNames{};std::vector<DataItem> dataItems;printf("等待網站返回數據中.....\n");// 發起 HTTP 請求獲取數據requests::Response resp = requests::get("http://124.222.37.232/api/list?ok=1");if (resp->status_code != 200) {printf("Request failed!\n");return std::make_pair(L"", dataItems);}// 解析返回的JSONJson json;try {json = Json::parse(resp->body);  // 使用 parse() 方法解析 JSON 字符串}catch (const nlohmann::json::parse_error& e) {printf("Failed to parse JSON: %s\n", e.what());return std::make_pair(L"", dataItems);}//===========打印所有數據======printf("Complete data:\n");printf("%s\n", json.dump().c_str());  // 打印全部網站獲取的數據// 檢查 JSON 數據中的字段if (json.is_object() && json.contains("total") && json["total"].is_number()) {int total = json["total"];printf("Total count: %d\n", total);if (json.contains("data") && json["data"].is_array()) {const nlohmann::json& dataArray = json["data"];srand(static_cast<unsigned int>(time(nullptr)));std::vector<const nlohmann::json*> filteredData;// 過濾符合條件的數據for (const nlohmann::json& item : dataArray) {if (item.is_object() && item.contains("name") && item["name"].is_string()&& item.contains("time") && item["time"].is_string()) {std::string time = item["time"].get<std::string>();int timeValue = std::stoi(time);if (timeValue < times) {filteredData.push_back(&item);}}}// 隨機選擇 numNamesToExtract 個名稱std::vector<size_t> randomIndices;if (filteredData.size() <= static_cast<size_t>(numNamesToExtract)) {// 數據量不足 numNamesToExtract 個時,選擇全部數據for (size_t i = 0; i < filteredData.size(); ++i) {randomIndices.push_back(i);}}else {// 數據量足夠時,隨機選擇 numNamesToExtract 個索引std::unordered_set<size_t> selectedIndices;while (selectedIndices.size() < static_cast<size_t>(numNamesToExtract)) {size_t randomIndex = rand() % filteredData.size();selectedIndices.insert(randomIndex);}randomIndices.assign(selectedIndices.begin(), selectedIndices.end());}// 提取名稱數據for (size_t index : randomIndices) {const nlohmann::json& item = *filteredData[index];std::string name = item["name"].get<std::string>();std::string time = item["time"].get<std::string>();std::wstring wideName = convertToWideString3(name);DataItem dataItem;dataItem.id = static_cast<int>(dataItems.size()) + 1;dataItem.name = wideName;dataItem.isChange = false;  // 默認設置為 false,因為無法比較之前的數據dataItems.push_back(dataItem);if (!concatenatedNames.empty()) {concatenatedNames += L",";}concatenatedNames += wideName;// 輸出 "time" 字段的值進行調試printf("Time value: %s\n", time.c_str());}const wchar_t* tCharStr = concatenatedNames.c_str();printf("Concatenated names: %ls\n", tCharStr);}}else {printf("Failed to parse 'total' field!\n");}// 打印 dataItems 中的數據printf("DataItems:\n");for (const DataItem& item : dataItems) {printf("ID: %d, Name: %ls \n", item.id, item.name.c_str());// 打印其他字段的值}return std::make_pair(concatenatedNames, dataItems);
}int main() {int numNamesToExtract = 3;int times = 50;std::pair<std::wstring, std::vector<DataItem>> result = GetServerData(numNamesToExtract, times);std::wstring concatenatedNames = result.first;std::vector<DataItem> dataItems = result.second;std::wcout << "Concatenated Names: " << concatenatedNames << std::endl;for (const auto& item : dataItems) {std::wcout << "ID: " << item.id << std::endl;std::wcout << "Name: " << item.name << std::endl;// 打印其他字段的值std::wcout << std::endl;}return 0;
}

運行結果:
在這里插入圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/161066.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/161066.shtml
英文地址,請注明出處:http://en.pswp.cn/news/161066.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【UE】用樣條線實現測距功能(上)

目錄 效果 步驟 一、創建樣條網格體組件3D模型 二、實現點擊連線功能 三、實現顯示兩點間距離功能 效果 步驟 一、創建樣條網格體組件3D模型 創建一個圓柱模型&#xff0c;這里底面半徑設置為10mm&#xff0c;高度設置為1000mm 注意該模型的坐標軸在如下位置&#xff1…

基于pytest的服務端http請求的自動化測試框架?

1、引言 我有一個朋友是做 Python 自動化測試的。前幾天他告訴我去參加一個大廠面試被刷了。 我問他是有沒有總結被刷下來的原因。他說面試官問了一些 pytest 單元測試框架相關的知識&#xff0c;包括什么插件系統和用力篩選。但是他所在的公司用的技術是基于 unittest 的&am…

Sentinel與SpringBoot整合

好的&#xff0c;以下是一個簡單的Spring Cloud整合Sentinel的代碼示例&#xff1a; 首先&#xff0c;在pom.xml中添加以下依賴&#xff1a; <dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel&l…

swift-基礎

print區別 print(1,2,3, separator: "-", terminator: "\n")//表示用-來分割//1-2-3 //terminator表示用\n作為終止符 var a "a",b "b" print(a b) //ab print("\(a)前面是a變量\(b)后面是b變量")變量 var name "…

Win10系統無法登錄Xbox live的四種解決方法

在Win10系統中&#xff0c;用戶可以登錄Xbox live平臺&#xff0c;暢玩自己喜歡的游戲。但是&#xff0c;有用戶卻遇到了無法登錄Xbox live的問題。接下來小編給大家詳細介紹四種簡單的解決方法&#xff0c;解決后用戶在Win10電腦上就能成功登錄上Xbox live平臺。 Win10系統無法…

Linux編程 文件操作 creat open

文件描述符 文件描述符在形式上是一個非負整數。實際上&#xff0c;它是一個索引值&#xff0c;指向內核為每一個進程所維護的該進程打開文件的記錄表。當程序打開一個現有文件或者創建一個新文件時&#xff0c;內核向進程返回一個文件描述符。 啟動一個進程之后&#xff0c;…

SquareCTF-2023 Web Writeups

官方wp&#xff1a;CTFtime.org / Square CTF 2023 tasks and writeups sandbox Description&#xff1a; I “made” “a” “python” “sandbox” “”“” nc 184.72.87.9 8008 先nc連上看看&#xff0c;只允許一個單詞&#xff0c;空格之后的直接無效了。 flag就在當…

(C)一些題2

1.在 C 語言中&#xff08;以 16位 PC 機為例&#xff09;,5種基本數據類型的存儲空間長度的順序為&#xff08;&#xff09; A . char < int < long int <float < double B . char int < long int<float <double C . char < int < long int …

inux應用開發基礎知識——串口應用編程(十一)

前言&#xff1a; 在Linux系統中&#xff0c;串口設備以文件的形式存在&#xff0c;通常位于/dev目錄下&#xff0c;如ttyS0、ttyUSB0等。這些設備文件可以用于讀取和寫入數據。要使用串口設備&#xff0c;需要打開相應的設備文件。在打開串口時&#xff0c;可以使用O_RDWR選項…

哈夫曼樹你需要了解一下

哈夫曼樹介紹哈夫曼數特點哈夫曼應用場景哈夫曼構建過程哈夫曼樹示例拓展 哈夫曼樹介紹 哈夫曼樹&#xff08;Huffman Tree&#xff09;是一種特殊的二叉樹&#xff0c;也被稱為最優二叉樹。在計算機科學中&#xff0c;它是由權值作為葉子節點構造出來的一種二叉樹。哈夫曼樹的…

05 取樣器(BeanShell和JSR223 Sampler)

一、取樣器作用 1、取樣器可以理解為Jmeter的橋梁&#xff0c;或者是Jmeter的加工廠&#xff1b; 2、Jmeter使用過程中&#xff0c;經常有些數據不能直接使用&#xff0c;需要加工后才能使用&#xff1b;這樣就用到了取樣器&#xff1b;但是這里存在問題&#xff0c;Jmeter中的…

Differences between package.json and pnpm-lock.yaml

1.pnpm-lock.yaml 是pnpm包管理工具生成的確保依賴包的版本在所有的環境里面都相同對依賴包的任何操作都會更新在該文件中&#xff0c;因此&#xff0c;需要確保提交到代碼倉庫中。包含了解析的依賴項和版本號。如下圖&#xff1a; 2.package.json 列出應用所需的依賴和元數…

批量修改文件名

原理&#xff1a; 利用 bat 的 REN 舊名字 新名字 命令 第一步&#xff1a; 【CtrlA】選中所有文件&#xff0c;按下【Shift】鍵右鍵任一文件夾彈出窗口選擇【復制為路徑】 第二步&#xff1a; 使用Excel技巧構造出 REN 舊名字 新名字 第三步&#xff1a; 用拼接好的命令…

【黑馬甄選離線數倉day01_項目介紹與環境準備】

1. 行業背景 1.1 電商發展歷史 電商1.0: 初創階段20世紀90年代&#xff0c;電商行業剛剛興起&#xff0c;主要以B2C模式為主&#xff0c;如亞馬遜、eBay等 ? 電商2.0: 發展階段21世紀初&#xff0c;電商行業進入了快速發展階段&#xff0c;出現了淘寶、京東等大型電商平臺&a…

(swjtu西南交大)數據庫實驗(數據庫需求分析):音樂軟件數據管理系統

實驗內容&#xff1a; 數據庫需求分析&#xff1a;各用戶組需求描述&#xff0c;繪出數據流圖&#xff08;詳細案例參見教材p333~p337&#xff0c;陶宏才&#xff0c;數據庫原理及設計&#xff0c;第三版&#xff09;&#xff1b; 一、選題背景 近年來&#xff0c;“聽歌”逐…

Ajax入門-Express框架介紹和基本使用

電腦實在忒垃圾了&#xff0c;出現問題耗費了至少一刻鐘time&#xff0c;然后才搞出來正常的效果&#xff1b; 效果鎮樓 另外重新安裝了VScode軟件&#xff0c;原來的老是報錯&#xff0c;bug。。&#xff1b; 2個必要的安裝命令&#xff1b; 然后建立必要的文件夾和文件&…

雷軍:我的程序人生路

今天有朋友發給我一篇我在20年前在BBS上寫的帖子。那還是1996年&#xff0c;我們通過電話線撥號連接到西點BBS上飆帖子玩的年代。那是一個互聯網混沌初開的年代&#xff0c;那是一個BBS和Email幾乎主宰了全部互聯網的年代&#xff0c;那是一個青春的理想和熱血沸騰的年代。 我…

新能源車將突破2000萬輛,漢威科技為電池安全保駕護航

近年來&#xff0c;我國新能源汽車銷量持續突破新高。據中汽協數據&#xff0c;1~10月&#xff0c;國內新能源汽車銷量達728萬輛&#xff0c;同比增長37.8%&#xff0c;市場占有率達到30.4%。隨著第四季度車市傳統旺季的到來&#xff0c;新能源消費需求將進一步釋放&#xff0c…

Python小灰灰

系列文章 序號文章目錄直達鏈接表白系列1浪漫520表白代碼https://want595.blog.csdn.net/article/details/1306668812滿屏表白代碼https://want595.blog.csdn.net/article/details/1297945183跳動的愛心https://want595.blog.csdn.net/article/details/1295031234漂浮愛心htt…

【軟件工程師從0到1】- 封裝 (知識匯總)

前言 介紹&#xff1a;大家好啊&#xff0c;我是hitzaki辰。 社區&#xff1a;&#xff08;完全免費、歡迎加入&#xff09;日常打卡、學習交流、資源共享的知識星球。 自媒體&#xff1a;我會在b站/抖音更新視頻講解 或 一些純技術外的分享&#xff0c;賬號同名&#xff1a;hi…