C++ #include 宏名称必须是标识符

c++ #include macro names must be identifiers

本文关键字:标识符 #include C++      更新时间:2023-10-16

我正在制作一个C++头文件用于学习目的。它应该给我数字的长度(无论是整数、浮点数、双精度数等),而不计算逗号。这是我的代码:

#ifndef NUMLEN_H
#define NUMLEN_H
#define <cstring>
int numlen (char numberLengthSample[])  //numlen - lenghth of the number, numberLengthSample - the number you put in.
{
    int numberLengthDummy = strlen (numberLengthSample);    //a temporary int used in counting the length
int numlenc = strlen (numberLengthSample);  //the true length of the number
while (numberLengthDummy>0)
{
    if (numberLengthSample[numberLengthDummy-1]=='.'||numberLengthSample[numberLengthDummy-1]==',')
    {
        numlenc--;
    }
    numberLengthDummy--;
}
return numlenc;
}
#endif // NUMLEN_H

但它给了我 3 个错误:1)(第 3 行)宏名称必须是标识符2)(第 7 行)"strlen"未在此范围内声明(显然)3) (第 5 行(从我的测试 .cpp 执行时)) 初始化 'int numlen(char*)' 的参数 1 [-fpermissive]|

我试图寻找答案,但没有占上风。任何帮助将不胜感激:)。

在C++中,您必须#include标头而不是#define它们:

#ifndef NUMLEN_H
#define NUMLEN_H
#include <cstring>

它与问题无关,但您应该只在头文件中声明函数并在源文件中实现它们。

问题是因为你使用的是 #define 而不是 #include,它应该是:

#include <cstring>