【问题标题】:C++ typeid.name() only returns char "c" [closed]C++ typeid.name() 只返回 char "c" [关闭]
【发布时间】:2014-03-24 19:43:12
【问题描述】:

我不完全确定这里发生了什么。我猜是因为我的输入是一个字符串,我一次循环一个字符,它总是以 char 类型返回。

我很确定一个字符串实际上是 char*。我能想到解决这个问题的唯一方法是包含并检查它是什么类型的字符,但我想避免这样做。有没有使用 typeid.name() 的替代方法来找出 char 是什么?

我正在使用 gcc 编译器

voidQueue outQueue;
string temp = "32ad1f-31f()d";

int i = 0;
while(temp[i] != '\0')
{
    outQueue.enqueue(temp[i]);
    i++;
}

template<typename T>
void voidQueue::enqueue(T data)
{
    T *dataAdded = new T;
    *dataAdded = data;
    string type(typeid(data).name());
    cout<< type;
    myQueue::enqueue((void *)dataAdded,type);
} 

【问题讨论】:

  • 请注意,name 返回的是实现定义的字符串。
  • datachar。你想解决什么问题?
  • 我希望它认识到 char('9') 实际上是一个 int
  • typeid 不会告诉您有关 char 所持有的值的任何信息。您可以使用std::isdigit。看我的回答。

标签: c++ pointers char void typeid


【解决方案1】:

我希望它认识到 char('9') 实际上是一个 int

您可以为此使用std::isdigit

#include <cctype>

bool digit = std::isdigit(static_cast<unsigned char>(temp[i]);

【讨论】:

  • 我想避免这样做,但我认为这是我能够做到这一点的唯一方法。至少现在我会这样做,感谢您的意见。
【解决方案2】:

在您的示例中,Tchargcctypeid(char).name() 返回 "c",如以下程序所示:

#include <iostream>
#include <typeinfo>

int main() {
  std::cout << typeid(char).name() << std::endl;
  std::cout << typeid(short).name() << std::endl;
  std::cout << typeid(int).name() << std::endl;
  std::cout << typeid(long).name() << std::endl;
}

在我的编译器上,这会打印出来

c
s
i
l

鉴于name() 字符串是实现定义的,这是合规行为。

【讨论】:

  • 如果打印出Ph你知道是什么类型吗?
  • @NPE,你有这些列表的来源吗?例如,我得到“x”,但我不知道它是什么:-/
猜你喜欢
  • 2015-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-01
相关资源
最近更新 更多