【问题标题】:C++ read int16_t (G++ compiler)C++ 读取 int16_t(G++ 编译器)
【发布时间】:2013-05-29 17:51:34
【问题描述】:

我需要在 stdint.hint16_t 中存储价值。如何从用户终端读取此值?

这个答案 (So, we have int32_t, int16_t, uint64_t, etc.. But where are the atoi32, atoi16, atoui64, etc...?) 的方式不适用于 Ubuntu g++ 编译器。

我更喜欢使用标准 C++ 库。比如:

#include <cstdio> 
#include <stdint.h>
#include <iostream>

using namespace std;

int main ( void ) {
    char value [] = "111";
    int16_t tmp;

    if ( sscanf ( value, "%???", & tmp) == 1 ) cout << "OK" << endl;

    return 0;
}

或者是更好地读取标准整数然后转换它?

我不使用 C++11。

【问题讨论】:

  • 您使用的是 C++11 吗?如果是这种情况,您需要在字符串文字和标识符之间添加一个空格:scanf( "%" SCNd16, &amp;tmp);,否则它会将其解释为后缀。
  • 对不起,我忘记写了。我不使用 C++11,但谢谢。

标签: c++ stdint


【解决方案1】:

停止使用旧的 C 函数,开始使用 C++ 功能:

std::string value = "111";

std::istringstream is(value);
if (is >> tmp)
    std::cout << "OK\n";

如果您想从用户那里读取它,请改用std::cin

if (std::cin >> tmp)
    std::cout << "OK\n";

【讨论】:

  • 工作正常,谢谢:-)。我不知道为什么我认为该流不喜欢 stdint.h 中的类型。
  • @PeterK。在现代计算机上的大多数情况下,uint16_t 只是unsigned short 的别名。
  • stream io 真的会让 c 风格的 printf / scanf 语义过时吗? std>>cin>>>std::blah::blahblah::yaddaddadadada>>some_weird_anaconda_snake_long_expression 真的比好的 ole sscanf 优越得多吗?我还没有看到一个 C++ 开发人员会在这个问题上给我一个不合格的“是”。
  • @AlexK 更好,因为它完全是类型安全的。使用scanf 和family,您可以轻松地提供指向格式以外的其他类型的指针。诚然,一个好的编译器可能会在某些情况下发出警告,但是对于 C++ 输入流,您会收到一个错误。我会说它更好。
  • @Joachim 我可以看到人们愿意为了性能和便利而牺牲安全性。
猜你喜欢
  • 1970-01-01
  • 2011-02-02
  • 1970-01-01
  • 1970-01-01
  • 2012-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多