C++ Programming. Please Help!!!!

Pages: 12
I'm still confused.
??
for reversing a c-string with out pointer math takes several steps.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

// create the string.
char inputString[50];  // give me enough room in a c-style string for a word or two.
char outputString[50];  // a matching out put size.

// init the string.
for(int i =0; i < 50; i++)
{
       inputString[i] = (char)0;
}

cout << "Enter a word you would like to reverse:" << endl;
cin >> inputString;

// find the end of the string.

int nEndofString = 0;

// scan the string for the first null.
while(inputString[nEndofString])
{
      nEndofString++;
}

int nStartofString = 0; // the of the output string.

for(int nIndex = nEndofString; nIndex >=0; nIndex--)
{
     outputString[nStartofString] = inputString[nIndex];
     nStartofString++; // increment the position in the new string.
}

cout << "the reversed word is: " << outputString;


This is the way I would implement the core code of this project without pointer math and using c-style strings. If I was using c++ style strings it might look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

string inputString;
string outputString;

cout << "Enter a word you would like to reverse:" << endl;
cin >> inputString;

int nLength = inputString.length();
nLength--; // make the nLength 0-based instead of 1 based.

for(int nIndex = nLength; nIndex >= 0; nIndex--)
{
       outputString+=inputString[nIndex];
}

cout << "the reversed word is: " << outputString;


If I were to this in one string I would have to have move one character into a temporary holder and move the target to the current working position then place the temp in to the target position. This operation would be easier to do from a c-style string than a c++ style string and it has to do with the way memory is managed in the c++ style string.


A c-style string is nothing more than a simple array.
Last edited on
Thanks so much. Now I just need to read the string from file.
Please Help!!!! Thanks so much.
Topic archived. No new replies allowed.
Pages: 12