This is an atoi()
I am trying to understand. In order to compile with the non-existing library, I called it m()
.
There are several lines of codes I am confused about, mainly char *
issues.
My questions are listed after the code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int m( char* pStr ) {
int iRetVal = 0;
int iTens = 1;
cout << "* pStr: " << * pStr << endl; // line 1
if ( pStr ) {
char* pCur = pStr;
cout << "* pCur: " << * pCur << endl;
while (*pCur) {
//cout << "* pCur: " << * pCur << endl; //line 2
pCur++; }
cout << "pCur: " << pCur << endl; //line 3
cout << "* pCur: " << * pCur << endl; //line 4
pCur--;
cout << "pCur: " << pCur << endl; //line 5
while ( pCur >= pStr && *pCur <= '9' && *pCur >= '0' ) {
iRetVal += ((*pCur - '0') * iTens);
pCur--;
iTens *= 10; } }
return iRetVal; }
int main(int argc, char * argv[])
{
int i = m("242");
cout << i << endl;
return 0;
}
Output:
* pStr: 2
* pCur: 2
pCur:
* pCur:
pCur: 2
242
Questions:
line 1: Why the cout is 2? *
pStr
was passed in as a pointer tochar
by 242, isn't supposed to be 242 instead?
line 2: I have to comment out thiscout
since it looks like it is in a infinite loop.What doeswhile (*pCur)
mean? And why do we need this loop?
line 3: Why it doesn't print out anything?
line 4: Why it doesn't print out anything?
line 5: Why does it print out 2 now after it got decremented?