04 调用QString::fromStdString导致程序崩溃

在VS2015环境下使用QT5.9时,调用QString::fromStdString函数会导致程序崩溃,原因是Debug模式下错误地引用了Release版本的QCore.dll(变为QCored.dll)。解决方法是确保在Debug和Release模式下正确引用对应的QT库文件。

项目场景

VS2015+QT5.9


问题描述

调用QString::fromStdString导致程序崩溃

#include <string>
using namespace std;

#include <qtcore/qstring>

int main() {
    string s = "111";
    QString ss = QString::fromStdString(s);
    return 0;
}

原因分析

Debug模式下引用了Release版本的库(QCore.dll改为QCored.dll)
(更深层原因未知)

解决方案

Debug模式下QT引用库QCored.dll
Release模式下QT引用库QCored.dll

要将实现最小生成树问题的C++代码放入相应文件并在Qt平台成功运行,可按以下方式操作: 创建Qt项目 打开Qt Creator,选择“File” -> “New File or Project”,在弹出的对话框中选择“Qt Widgets Application”,然后按照向导完成项目创建。 代码文件安排 头文件(.h):将图和边的类定义、算法声明等代码放入头文件中。例如,创建一个名为graph.h的文件,内容如下: C++ #ifndef GRAPH_H #define GRAPH_H #include <vector> #include <string> #include <algorithm> class Edge { public: std::string src, dest; int weight; Edge(std::string s, std::string d, int w) : src(s), dest(d), weight(w) {} bool operator<(const Edge& other) const { return weight < other.weight; } }; class Graph { public: std::vector<std::string> vertices; std::vector<Edge> edges; void addEdge(std::string src, std::string dest, int weight) { edges.emplace_back(src, dest, weight); if (std::find(vertices.begin(), vertices.end(), src) == vertices.end()) { vertices.push_back(src); } if (std::find(vertices.begin(), vertices.end(), dest) == vertices.end()) { vertices.push_back(dest); } } }; std::vector<Edge> kruskal(const Graph& graph); std::vector<Edge> prim(const Graph& graph, const std::string& start); #endif // GRAPH_H 源文件(.cpp):将算法的实现代码放入对应的源文件中。创建graph.cpp文件,内容如下: C++ #include "graph.h" std::vector<Edge> kruskal(const Graph& graph) { std::vector<Edge> result; std::vector<Edge> sortedEdges = graph.edges; std::sort(sortedEdges.begin(), sortedEdges.end()); std::vector<std::string> parent; for (const auto& vertex : graph.vertices) { parent.push_back(vertex); } auto find = [&](const std::string& vertex) { std::string root = vertex; while (root != parent[std::find(graph.vertices.begin(), graph.vertices.end(), root) - graph.vertices.begin()]) { root = parent[std::find(graph.vertices.begin(), graph.vertices.end(), root) - graph.vertices.begin()]; } std::string current = vertex; while (current != root) { std::string next = parent[std::find(graph.vertices.begin(), graph.vertices.end(), current) - graph.vertices.begin()]; parent[std::find(graph.vertices.begin(), graph.vertices.end(), current) - graph.vertices.begin()] = root; current = next; } return root; }; auto unite = [&](const std::string& u, const std::string& v) { std::string root1 = find(u); std::string root2 = find(v); if (root1 != root2) { parent[std::find(graph.vertices.begin(), graph.vertices.end(), root1) - graph.vertices.begin()] = root2; } }; for (const auto& edge : sortedEdges) { std::string u = edge.src; std::string v = edge.dest; if (find(u) != find(v)) { result.push_back(edge); unite(u, v); } } return result; } std::vector<Edge> prim(const Graph& graph, const std::string& start) { std::vector<Edge> result; std::vector<std::string> mstSet; mstSet.push_back(start); while (mstSet.size() < graph.vertices.size()) { Edge minEdge("", "", INT_MAX); for (const auto& vertex : mstSet) { for (const auto& edge : graph.edges) { if ((edge.src == vertex && std::find(mstSet.begin(), mstSet.end(), edge.dest) == mstSet.end()) || (edge.dest == vertex && std::find(mstSet.begin(), mstSet.end(), edge.src) == mstSet.end())) { if (edge.weight < minEdge.weight) { minEdge = edge; } } } } result.push_back(minEdge); if (std::find(mstSet.begin(), mstSet.end(), minEdge.src) == mstSet.end()) { mstSet.push_back(minEdge.src); } else { mstSet.push_back(minEdge.dest); } } return result; } 主窗口文件:将图形界面和交互逻辑的代码放入主窗口的头文件和源文件中。mainwindow.h文件内容如下: C++ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QFile> #include <QTextStream> #include <QMessageBox> #include <QVBoxLayout> #include <QPushButton> #include <QLineEdit> #include <QTextEdit> #include "graph.h" QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void importFile(); void runKruskal(); void runPrim(); private: Ui::MainWindow *ui; Graph graph; QPushButton *importButton; QLineEdit *startInput; QPushButton *kruskalButton; QPushButton *primButton; QTextEdit *resultText; }; #endif // MAINWINDOW_H mainwindow.cpp文件内容如下: C++ #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { QWidget *centralWidget = new QWidget(this); setCentralWidget(centralWidget); QVBoxLayout *layout = new QVBoxLayout(centralWidget); importButton = new QPushButton("导入文件", this); layout->addWidget(importButton); connect(importButton, &QPushButton::clicked, this, &MainWindow::importFile); startInput = new QLineEdit(this); startInput->setPlaceholderText("输入起点城市"); layout->addWidget(startInput); kruskalButton = new QPushButton("克鲁斯卡尔算法", this); layout->addWidget(kruskalButton); connect(kruskalButton, &QPushButton::clicked, this, &MainWindow::runKruskal); primButton = new QPushButton("普里姆算法", this); layout->addWidget(primButton); connect(primButton, &QPushButton::clicked, this, &MainWindow::runPrim); resultText = new QTextEdit(this); resultText->setReadOnly(true); layout->addWidget(resultText); } MainWindow::~MainWindow() { delete ui; } void MainWindow::importFile() { QFile file("cities.txt"); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream in(&file); graph.edges.clear(); graph.vertices.clear(); while (!in.atEnd()) { QString line = in.readLine(); QStringList parts = line.split(","); if (parts.size() == 3) { std::string src = parts[0].toStdString(); std::string dest = parts[1].toStdString(); int weight = parts[2].toInt(); graph.addEdge(src, dest, weight); } } file.close(); QMessageBox::information(this, "导入成功", "城市信息导入成功"); } else { QMessageBox::critical(this, "导入失败", "无法打开文件"); } } void MainWindow::runKruskal() { std::vector<Edge> result = kruskal(graph); QString output; for (const auto& edge : result) { output += QString::fromStdString(edge.src) + " - " + QString::fromStdString(edge.dest) + " : " + QString::number(edge.weight) + "\n"; } resultText->setPlainText(output); } void MainWindow::runPrim() { std::string start = startInput->text().toStdString(); if (std::find(graph.vertices.begin(), graph.vertices.end(), start) == graph.vertices.end()) { QMessageBox::critical(this, "输入错误", "起点城市不存在"); return; } std::vector<Edge> result = prim(graph, start); QString output; for (const auto& edge : result) { output += QString::fromStdString(edge.src) + " - " + QString::fromStdString(edge.dest) + " : " + QString::number(edge.weight) + "\n"; } resultText->setPlainText(output); } 主函数文件:main.cpp文件内容如下: C++ #include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } 编译和运行 在Qt Creator中,点击“构建” -> “构建项目”,如果没有错误,再点击“运行”,程序将启动并显示图形界面。 然后怎么做
09-19
QObject::connect(player,&QMediaPlayer::positionChanged, this, [=](qint64 position) mutable { //滚动显示三行歌词 if (!lyricsLoaded) { QString filePath = playlist->currentMedia().toString(); QString localFilePath = QUrl(filePath).toLocalFile(); std::wstring wpath = localFilePath.toStdWString(); TagLib::FLAC::File file(wpath.c_str()); TagLib::Ogg::XiphComment *comments = file.xiphComment(false); const char* lyricFields[] = {"LYRICS", "UNSYNCEDLYRICS", "LYRIC"}; // 支持多个常见键名 for (const char* field : lyricFields) { if (comments->contains(field)) { TagLib::StringList lyricsList = comments->fieldListMap()[field]; QString lyrics =QString::fromStdString(lyricsList.front().to8Bit(true)); QRegularExpression regex(R"(\[(\d+):(\d+)\.(\d+)\](.*))"); QRegularExpressionMatchIterator it = regex.globalMatch(lyrics); while (it.hasNext()) { QRegularExpressionMatch match = it.next(); qint64 min = match.captured(1).toLong(); qint64 sec = match.captured(2).toLong(); qint64 ms = match.captured(3).toLong(); qint64 totalMs = (min * 60000) + (sec * 1000) + ms * 10; lyricMap[totalMs] = match.captured(4).trimmed(); } lyricsLoaded = true; } } } if (!lyricMap.isEmpty()) { // 查找当前歌词 auto it = lyricMap.upperBound(position); // 第一个大于position的键 if (it != lyricMap.begin()) { --it; } QString prevLine, currentLine, nextLine; // 获取三行歌词 if (it != lyricMap.end()) {currentLine = it.value();} // 当前行 auto prevIt = it; // 上一行 if (prevIt != lyricMap.begin()) { --prevIt; prevLine = prevIt.value(); } auto nextIt = it; // 下一行 if (nextIt != lyricMap.end()) { ++nextIt; if (nextIt != lyricMap.end()) { nextLine = nextIt.value(); } } QString displayText = QString("%1<br><font color='red' size='3'>%2</font><br>%3") .arg(prevLine, currentLine, nextLine); lyricLabel->setText(displayText); } });在这个代码的基础上修改使切歌后歌词更新成新歌的歌词
09-16
Response MESInterface::Send(const string & info, const string & apiPath, string m_username, string m_password) { // 检查连接状态 if (m_connectionState != ConnectionState::Connected) { CreateSocket(); // 尝试重连 // 重连后仍然失败 if (m_connectionState != ConnectionState::Connected) { Response resp; resp.Code = NETWORK_ERROR; resp.Msg = "MES connection not established"; return resp; } } // 检查2:物理连接健康检查 if (!IsConnectionAlive()) { ResetConnection(); CreateSocket(); if (m_connectionState != ConnectionState::Connected) { return { NETWORK_ERROR, "Reconnection failed after dead connection detected" }; } } Response resp; if (!m_pConnection) { resp.Code = NETWORK_ERROR; resp.Msg = "Not connected to server. Call Connect() first."; return resp; } try { auto deleter = [](CHttpFile* p) { if (p) delete p; }; std::unique_ptr<CHttpFile, decltype(deleter)> pFile( m_pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, m_GFunction.String2CString(apiPath)), deleter); // 设置请求头 //Post请求 /* Content - Type: application / json Authorization : Basic Auth 用户名 : master 密码 : 88Jjlh$&efwObdDQ*/ CString strHeaders = _T("Content-Type: application/json\r\n"); strHeaders += _T("Authorization: Basic ") + EncodeBasicAuth(m_GFunction.String2CString(m_username), m_GFunction.String2CString(m_password)) + _T("\r\n"); // 转换请求数据 CString strData = m_GFunction.String2CString(info); addInfo( "请求头:" + m_GFunction.CString2String(strHeaders) + "请求体:" + info); pFile->SendRequest ( strHeaders, (DWORD)strHeaders.GetLength(), (LPVOID)(LPCTSTR)strData, (DWORD)strData.GetLength() ); DWORD dwStatusCode; pFile->QueryInfoStatusCode(dwStatusCode); CString strResponse; if (dwStatusCode == HTTP_STATUS_OK) { TCHAR szBuffer[1024]; while (pFile->Read(szBuffer, 1023) > 0) { strResponse += szBuffer; } } if (dwStatusCode != HTTP_STATUS_OK) { resp.Code = HTTP_ERROR; resp.Msg = QString::number(dwStatusCode); return resp; } resp.Msg = QString::fromLocal8Bit(m_GFunction.CString2String(strResponse).c_str()); pFile->Close(); } catch (CInternetException* pEx) { TCHAR szError[1024]; pEx->GetErrorMessage(szError, 1024); resp.Msg = QString::fromLocal8Bit(m_GFunction.CString2String(szError).c_str());// 异常信息写入resultMSG pEx->Delete(); resp.Code = NETWORK_ERROR; return resp; } resp.Code = SUCCESS; return resp; } 500错误
最新发布
09-29
#include "mainwindow.h" #include <qmenubar.h> #include <regex> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { createUI(); setupMenu(); setWindowTitle("Rust词法分析器"); resize(800, 600); } void MainWindow::createUI() { QSplitter *splitter = new QSplitter(this); // 左侧分类树 treeWidget = new QTreeWidget; treeWidget->setHeaderLabel("词法分类"); // 右侧代码视图 codeView = new QTextEdit; codeView->setReadOnly(true); splitter->addWidget(treeWidget); splitter->addWidget(codeView); setCentralWidget(splitter); } void MainWindow::setupMenu() { QMenu *fileMenu = menuBar()->addMenu("文件"); QAction *openAct = new QAction("打开", this); connect(openAct, &QAction::triggered, this, &MainWindow::openFile); fileMenu->addAction(openAct); } void MainWindow::openFile() { QString path = QFileDialog::getOpenFileName(this, "打开Rust文件", "", "Rust文件 (*.rs)"); if (path.isEmpty()) return; QFile file(path); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::warning(this, "错误", "无法打开文件"); return; } QTextStream in(&file); QString content = in.readAll(); file.close(); codeView->setText(content); analyzeCode(content); } // 核心词法分析函数 void MainWindow::analyzeCode(const QString &content) { tokens.clear(); treeWidget->clear(); // 正则表达式模式(按优先级排序) const std::vector<std::pair<QString, QString>> patterns = { {"COMMENT", R"((//.*|/\*[\s\S]*?\*/))"}, {"STRING", R"((r?#*".*?"#*))"}, {"KEYWORD", R"(\b(as|async|await|break|const|continue|dyn|else|enum|extern|fn|for|if|impl|in|let|loop|match|mod|move|mut|pub|ref|return|self|Self|static|struct|super|trait|type|union|unsafe|use|where|while)\b)"}, {"LITERAL", R"((0b[01_]+|0o[0-7_]+|0x[\dA-Fa-f_]+|[\d_]+(\.[\d_]+)?([eE][+-]?[\d_]+)?))"}, {"OPERATOR", R"(([-+*/%=&|<>!^]=?|<<|>>|&&|\|\||\.\.=|\.\.))"}, {"DELIMITER", R"([{}()\[\],;:])"}, {"IDENT", R"(([_a-zA-Z][_a-zA-Z0-9]*))"} }; // 逐行分析 int lineNum = 1; for (const QString &line : content.split('\n')) { QString remaining = line.trimmed(); while (!remaining.isEmpty()) { bool matched = false; for (const auto &[type, regexStr] : patterns) { std::regex reg(regexStr.toStdString(), std::regex_constants::icase); std::smatch match; std::string str = remaining.toStdString(); if (std::regex_search(str, match, reg, std::regex_constants::match_continuous)) { QString value = QString::fromStdString(match[1]); tokens.push_back({type, value, lineNum}); addTreeItem(type, tokens.back()); remaining.remove(0, match[1].length()); remaining = remaining.trimmed(); matched = true; break; } } if (!matched) { qDebug() << "无法解析: " << remaining.left(10); break; } } lineNum++; } } void MainWindow::addTreeItem(const QString &category, const Token &token) { QList<QTreeWidgetItem*> items = treeWidget->findItems(category, Qt::MatchExactly); QTreeWidgetItem *categoryItem; if (items.isEmpty()) { categoryItem = new QTreeWidgetItem(treeWidget); categoryItem->setText(0, category); } else { categoryItem = items.first(); } QTreeWidgetItem *child = new QTreeWidgetItem(); child->setText(0, QString("%1 (Line %2)").arg(token.value).arg(token.line)); categoryItem->addChild(child); treeWidget->expandAll(); } 分析代码,检查有无问题
03-23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值