简体   繁体   中英

C++ read int16_t (G++ compiler)

I need store value in int16_t from stdint.h . How can I read this value from user's terminal?

The way from this answer ( So, we have int32_t, int16_t, uint64_t, etc.. But where are the atoi32, atoi16, atoui64, etc...? ) doesn't work on Ubuntu g++ compiler.

I prefer use standard C++ libraries. Something like:

#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;
}

Or is better read standard integer and then convert it?

I don't use C++11.

Stop using old C functions, and start using C++ functionality:

std::string value = "111";

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

If you want to read it from the user, then use std::cin instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM