其他分享
首页 > 其他分享> > C将int转换为字符串内联

C将int转换为字符串内联

作者:互联网

我的问题似乎很基本但我无法找到解决方案.我需要编写一个代码,通过报告异常抛出的行和位置来帮助调试.问题是__LINE__是一个int值,我在下面的代码中使用std :: string(line)转换成字符串时遇到问题:

#pragma once

#include <stdexcept>
#include <cstring>


class CRuntime_error_line: public std::runtime_error
{
public:
    CRuntime_error_line(const char * msg, const char * file,int line)
        :runtime_error(std::string(msg)+" @"+":"+std::string(line)){}
};

#define runtime_error_line(msg) CRuntime_error_line(msg,__FILE__,__LINE__)

似乎std :: string(line)无法将int转换为字符串,其他解决方案建议在线无法实现内联,我不知道如何在第二行调用基础构造函数!

编译输出:

log.h: In constructor ‘CRuntime_error_line::CRuntime_error_line(const
char*, const char*, int)’: log.h:10:124: error: invalid conversion
from ‘int’ to ‘const char*’ [-fpermissive] CRuntime_error_line(const
char * msg, const char * file,int
line):runtime_error(std::string(msg)+” @”+”:”+std::string(line)){}

(使用g和linux环境)

编辑:

应该以这种方式调用宏:

throw runtime_error_line("Invalid somethihng ...!");

解决方法:

正如Borgleader所建议的那样,std :: to_string是你的解决方案.它还会为你构造一个临时的std :: string,所以不需要从msg构造一个临时字符串:

#pragma once

#include <stdexcept>
#include <cstring>
#include <string> // Add this to support std::to_string


class CRuntime_error_line: public std::runtime_error
{
public:
    CRuntime_error_line(const char* msg, const char* file, int line)
        : runtime_error(msg + " @:"s + std::to_string(line)){} // Use std::to_string here
};

#define runtime_error_line(msg) CRuntime_error_line(msg, __FILE__, __LINE__)

如果没有C 11,你仍然可以做到这一点,它不是那么干净:

#pragma once

#include <stdexcept>
#include <cstring>
#include <sstream> // Use to include std::ostringstream    

class CRuntime_error_line: public std::runtime_error
{
public:
    CRuntime_error_line(const char* msg, const char* file, int line)
        : runtime_error(static_cast<std::ostringstream&>(std::ostringstream() << msg << " @:" << line).str()){} // Use std::ostringstream here
};

#define runtime_error_line(msg) CRuntime_error_line(msg, __FILE__, __LINE__)

标签:data-conversion,c,string
来源: https://codeday.me/bug/20190830/1766956.html