![]() |
Read char as number value
say for example I have a file called key.txt
:
and I wish to read from this file, digit by digit. with in being the ifstream object, I would write: :
char temp;Now, I want this character to be converted to an int of the same value. so for Example, if I read the '4' character, I want to convert it into a int (4). the problem is that if I typecast it by doing this: :
I get the ASCII value, rather then the numerical value. How would I accomplish what I want? Thanks :) |
Does C++ use or have an equivilant of the atoi() function?
|
why can't c++ just use the atoi function?...(uh, it can...it's C++, not B++ or R++, hell.)
out of ignorance, let me suggest something harder than it should be... if you're reading only ONE character at a time, then you only have to worry about the int values of 0-9. just use a switch to assign the correct integer value to the ascii value. ten cases, trivial problem. i'm sure there's a better way. |
Quote:
|
I'm with using atoi() ... no need to rewrite the wheel...
|
Also, you can do something like
:
a=temp-'0'; |
i would use that instead of atoi, since this doesn't do more than it needs to do - so it is faster.
|
Is this for you Password Generator? ;)
I don't know how to deal with files yet, but i know that if u give a "char" variable a number value, it would be converted into an ASCII Character. EG. :
char x=65;This is What you will get on your screen... :
Ai hope i helped you with this... |
Quote:
|
I believe that atoi() is for strings, not chars.
How about a simple subtraction... int val = int(n) - 48; Here's a quick sample... #include <iostream> #include <fstream> #include <cstring> using namespace std; int main() { string filepath = "D:\\ints.txt"; ifstream in(filepath.c_str()); if(!in.is_open()) { cerr << "Error opening " << filepath; return -1; } char n; int via_subtract; const int ASCII_ZERO = 48; in.get(n); while(!in.eof()) { via_subtract = int(n) - ASCII_ZERO; cout << "Input = \'" << n << "\'\tvia_subtract = " << via_subtract << "\n"; in.get(n); } in.close(); return 0; } Hope that helps |
| All times are GMT -5. The time now is 8:39 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC