I was wondering if there is any way to parse integers from a string (like in java)? Anyone know of a built in function in c++?

Recommended Answers

All 11 Replies

stringstream

atoi is a C function that works in C++.

e.g.:

#include <iostream>
#include <cstdio>
#include <cstring>

int main() {
    char s[80];
    int i;
    cin>>s;
    i = atoi(s);
    cout>>i;
    return 0;
}

My C++ is a little rusty, but that's my example. Using the String class might be a little dirrerent.

Rusty, indeed. :)

cout>>i;

->

cout<<i;

atoi() is a non-standard function;

atoi is part of the C89 standard.

hey fucktards, I wanted to know if I could parse a single integer from a string that contains multiple substrings** and integers -.-

hey ####tards, I wanted to know if I could parse a single integer from a string that contains multiple substrings** and integers -.-

Hey clown. Glad to hear you no longer want to know.

gobartatti - As we all can see, you are new to our community. One way of getting you noticed in a good way, and also, to be helped, is to obey the rules (which you agreed upon your registration) and not to embarrass yourself by your posts.

I see you have a question, but this thread in which you posted is 6 years old (threads older than 3 months shouldn't be replied, only if adding important/new information to the topic). I sugest you to start a new topic in wich to exaplain your needs/problems, also proving (by showing some code) that you'd tried to solve that issues.
Good luck.

Instead of atoi, use strtol() (string to long) or strtoll() (string to long long). They let you provide a pointer that will be set to the first unconvertable character. It will deal with +- leaders, and all the rest of that cruft. Perfectly fine in C++. If you are reading from a stream in C++, then you are probably better off using the syntax strm >> intvar such as cin >> anInt.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.