Arch1tect
Arch1tect

Reputation: 4281

How to convert string to long long

All the solution I found seem to use atoll but that takes char while I have a string. For example I read an input $100, put it into a string and check if the first char is $. Then I need to convert the substring to a long long type.

int main() {

    long long price;
    string priceStr;

    cin>>priceStr;
    if (priceStr[0] == '$') {
        price = convertToLongLong(priceStr.substr(1));//how?
    }else{
        cerr<<"error!";
    }

}

My input is : $100 Thanks!

EDIT: Maybe I'm not doing it in a proper way. My input stream is ID Name $price #quantity like below and I need all numbers to be long long and also check if $ and # sighs are at right place:

1 TV $1500 #50

2 LAPTOP $2000 #30

Upvotes: 0

Views: 10688

Answers (4)

charlotte
charlotte

Reputation: 1071

Try to use stoll

please refer http://www.cplusplus.com/reference/string/stoll/

I never tried this

Upvotes: 0

bdwain
bdwain

Reputation: 1745

read the docs for string http://www.cplusplus.com/reference/string/string/

there's a very obvious way to get a char* from a std::string in there

Upvotes: 0

Nathan Ernst
Nathan Ernst

Reputation: 4590

You've a couple of options, if the STL is your only option:

int main() {

    long long price;
    string priceStr;

    cin>>priceStr;
    if (priceStr[0] == '$') {
        std::istringstream is (priceStr.begin() + 1, priceStr.end());
        is >> price;
        if (!is)
            cerr << "fail!" << endl;
    }else{
        cerr<<"error!";
    }
}

If you can use Boost:

int main() {

    long long price;
    string priceStr;

    cin>>priceStr;
    if (priceStr[0] == '$') {
        price = boost::lexical_cast<long long>(&*priceStr.begin() + 1, priceStr.size() -1); // throws if it cannot convert.
    }else{
        cerr<<"error!";
    }
}

Note that there's no bounds checking in the second example, you'd surely want to implement that before doing what I've shown above. (i.e. check that priceStr.size() >= 2).

As others have suggested, you could use variants of stoll, but be aware these functions don't report errors well, if at all.

Upvotes: 1

jwalk
jwalk

Reputation: 1147

Use scanf

scanf("$%lld", &price);

edit

See above reference. Quick and easy way to format input.

if(scanf("%lld %s $%lld #%lld",
  &id, name, &price, &quantity)!=4) fprintf(stderr, "error!");

Otherwise see other answers for more common/standard solutions.

Upvotes: 1

Related Questions