如何在消息框上打印长变量(在c++中)
how to print a longvariable on a message box (in c++)
我写这段代码是为了计算一个学生在希腊入学考试中的分数。当程序计算分数并将其保存在变量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);
要打印一个长数字,我想我必须先把它变成一个字符串。但它仍然不能工作,我得到以下错误:
- 'to_string'未在此范围内声明
- 无法将'std::string'转换为'const CHAR*'对于参数'2'到'int MessageBoxA(HWND__, const CHAR, const CHAR*, UINT)'
由于我最近才开始学习一些关于图形的东西,这里可能会有一些非常愚蠢的错误,所以请理解…
问题1:将int
转换为std::string
to_string
没有声明,所以编译器不知道你想做什么。我将假设moria
是int
(或某个数字)。
要将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*
您的第二个问题是MessageBox
将const 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);
值得注意的是两位评论者@π
您似乎没有包含<string>
,因此没有声明to_string()
。
问题2已经由上面的答案解决了
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 将包含C样式数组的对象初始化为成员变量(C++)
- 当vector是tje全局变量时,c++中vector的内存管理
- 通过多个头文件使用常量变量
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 执行函数时导致崩溃的变量
- 变量没有改变?通过向量的函数调用