如何在消息框上打印长变量(在c++中)

how to print a longvariable on a message box (in c++)

本文关键字:变量 c++ 打印 消息      更新时间:2023-10-16

我写这段代码是为了计算一个学生在希腊入学考试中的分数。当程序计算分数并将其保存在变量moria中时,我希望这个数字出现在弹出窗口中。

#include <iostream>
#include <windows.h>
using namespace std;
int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)

最后一部分是计算分数和出现消息框代码的地方,它是:

mathks= mathk*0.7 + mathkp*0.3 ;
aodes= aode*0.7 + aodep*0.3 ;
fysks= fysk*0.7 + fyskp*0.3 ;
aeps= aep*0.7 + aepp*0.3 ;
ek8eshs= ek8esh*0.7 + ek8eshp*0.3 ;
mathgs= mathg*0.7 + mathgp*0.3 ;
gvp=(mathks+aodes+fysks+aeps+ek8eshs+mathgs)/6 ;
x=mathk*1.3 ;
y=fysk*0.7 ;
moria=(gvp*8+x+y)*100 ;
string moria2 = to_string(moria);
MessageBox(NULL, moria2, "arithmos moriwn", NULL);

要打印一个长数字,我想我必须先把它变成一个字符串。但它仍然不能工作,我得到以下错误:

  1. 'to_string'未在此范围内声明
  2. 无法将'std::string'转换为'const CHAR*'对于参数'2'到'int MessageBoxA(HWND__, const CHAR, const CHAR*, UINT)'

由于我最近才开始学习一些关于图形的东西,这里可能会有一些非常愚蠢的错误,所以请理解…

问题1:将int转换为std::string

to_string没有声明,所以编译器不知道你想做什么。我将假设moriaint(或某个数字)。

要将int转换为std::string,你应该看看这个问题,它强调了三种很好的方法:atoi, std::ostringstream,以及最近也是最好的std::to_string(看起来你正在尝试使用)。

要正确使用std::to_string,您应该编写以下内容:

std::string moria2 = std::to_string(moria);

请注意,std::to_string仅来自c++ 11,我假设您正在使用。如果您没有c++ 11,请选择std::ostingstream:

std::ostringstream oss;
oss << moria;
std::string moria2 = oss.str();

作为旁注,您应该倾向于指示性地命名变量,而不仅仅是附加数字。

问题#2:将std::string转换为const char*

您的第二个问题是MessageBoxconst char*作为其第二个参数,而您提供的是std::string(编译器无法隐式转换为);然而,std::string优雅地为您提供了这样做的方法:std::string::c_str()。因此,您的代码应该是:

MessageBox(NULL, moria2.c_str(), "arithmos moriwn", NULL);

MessageBox(NULL, std::to_string(moria).c_str(), "arithmos moriwn", NULL);

值得注意的是两位评论者@π ντα ν ν(如果这是不正确的,我道歉)和@Jonathan Potter,他们首先指出了这一点。

您似乎没有包含<string>,因此没有声明to_string()

问题2已经由上面的答案解决了