Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

atoi() confusion 1

Status
Not open for further replies.

Kalisto

Programmer
Joined
Feb 18, 2003
Messages
997
Location
GB
Below is a code fragment, that I am using to try and check that a drive string entered points to a valid drive.

Code:
//Check to see if the drive is a valid drive
char* s = new char;
*s = ptrTarget[0];

int nDrv = atoi(s);
if (!_chdrive(nDrv))
{
	AfxMessageBox("The Target Drive does not exist !",MB_OK);
	return; 
}
Watching via the debugger, nDrv is only ever set to 0, which implies that atoi() cannot convert the current value into an integer.

ptrTarget is defined elsewhere in the same function as being a char*, and contains the string "Q:\\test", which is not a valid path on my PC.

So my starter for 10 is, whats happening here that I don't understand ?

And as a bonus question, is _chdrive() the easiest way to check if a drive is valid (I know I still need to handle the fact that the string might be upper or lower case)

K
 
I guess ptrTarget is a char** or a char[][]?
and ptrTarget[0] is something like "3" (3 = disk C)?

Ion Filipski
1c.bmp

ICQ: 95034075
AIM: IonFilipski
filipski@excite.com
 
This is what happens (ptrTarget="Q:\\test"):


char* s = new char;
*s = ptrTarget[0]; //*s now = 'Q'

int nDrv = atoi(s); //nDrv=atoi("Q")->you see what's wrong here? You can't convert a Q to an integer... it's not a number.


Greetings,
Rick
 
Surely internally the q is stored as 113 ('q' iirc) and not as q.

or am I missing your point entirely ?

K
 
no, it should not be 'Q' nor "Q", only a valid "number"
like "20", not '20'
or "3" and not '3' (disk C)

Ion Filipski
1c.bmp

ICQ: 95034075
AIM: IonFilipski
filipski@excite.com
 
Damn, I just came rushing back here when I realised what I had done, to post that I am just plain stupid.

I know, I have to convert the drive letter into a number first.

Sorry, and thanks for the hints that I didn't notice.

K
 
in this case forget atoi
int nDrv;
if(ptrTarget[0] >= 'a' and ptrTarget[0] >= 'z')
{
nDrv = (int)ptrTarget[0] - 'a' + 1;
}else if(ptrTarget[0] >= 'A' and ptrTarget[0] >= 'Z')
{
nDrv = (int)ptrTarget[0] - 'A' + 1;
}else is wrong drive letter

if (!_chdrive(nDrv))
{

Ion Filipski
1c.bmp

ICQ: 95034075
AIM: IonFilipski
filipski@excite.com
 
sorry:
ptrTarget[0] <= 'z'

Ion Filipski
1c.bmp

ICQ: 95034075
AIM: IonFilipski
filipski@excite.com
 
Cheers, that more or less how I had re-written it, but it's nice to know that I can still do soemthings right, after my recent debacles !)

K
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top