I need to create a program that will accept a string inserted by the user, which represents an unsigned int. I need to convert this string to a vector of ints, and then convert the number to binary and hexadecimal. This is what I have so far:
#include %26lt;iostream%26gt;
#include %26lt;vector%26gt;
#include %26lt;string%26gt;
#include %26lt;cstdlib%26gt;
using namespace std;
int main(void)
{
cout%26lt;%26lt;"Input a decimal:"%26lt;%26lt;endl;
string s;
cin%26gt;%26gt;s;
vector%26lt;int%26gt;n(s.length());
for(int i = 0; i %26lt; n.size(); i = i + 1)
{
n[i] = s[i] - 48;
}
return 0;
}
Converting a string, to a vector of ints, to binary, to hexadecimal. (C++)?
Your code assumes that the string entered only contains ASCII digits. You should explicitly check for this:
if ( isdigit( s[i] ) ) {
Next, you can also use a standard function to convert a string to an integer for you:
n[i] = atoi( s[i] );
(if you ever want to convert the entire string to a single integer, you could use strtol() ).
Give these a whirl and see where you end up. Go to the URL below and type "atoi" in the search field.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment