reversing array contents


Hi all

Below is some code, it read a string, counts the words and then extracts to an array.  

I have two for loops from lines 53 to 62 that  are supposed to print out the array contents, the first one i++, kinda works
although i want the format to be abc def instead of
abc
def

and the second does not i--. I would like to know why it doesn't and any suggestions to fix it would be gratefully recieved.

// rev1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string.h>
#include <conio.h>
#include <iostream>
#include <string>
#include <list>

int wordCount(const char *s);
int wordExtract(const char *s,  char **word, unsigned int size);


int a;
 

int _tmain(int argc, _TCHAR* argv[])
{
     using namespace std;      

{
     string s1;
       string one;

     cout << "Enter your sentence: " << endl;

     char ch='a';
     string s2;

     while(ch!='\r')
     {
       ch=getche();
       s2 = s1;
       s1 += ch;
     }

     cout << "The user specified string is : ";
     cout << s2  << endl;
     int  n1 =wordCount(s2.c_str());
       //cout << n1 << endl;

     char **word = new char* [n1];
       //int m = wordExtract(s2,word,n1);
      int m = wordExtract(s2.c_str(),word,n1);

      //cout << *(word) <<endl;
      //cout <<   << endl;
      a = s2.length();
      cout << a << endl;
      
//************************************************

      for (int i=0; i<=a; i++)
      {
      cout << word[i] << endl;       //this works
      }

      //for (int i=a; i>=0; i--)
      //{
      //cout << word[i] << endl;        //this does not ???
      //}
//************************************************
      //cout << one << endl;
      



      for(int i=0;i < m;i++) delete []word[i];
      delete []word;

      //cout << *word << endl;
      return 0;
     }
      
}
int wordCount(const char *s2)
{      
     unsigned int pos=0,count=0, len= strlen(s2);
       while(pos < len)
     {
          while(isspace( *(s2+pos)) && pos < len)  // will return o for s1,
               pos ++;     // go through space

          if(pos < len) count ++;
          while(!isspace( *(s2+pos)) && pos < len)
               pos ++; // go through non-space  
     
     }
     
     return count;
}

int wordExtract(const char *s2,  char **word, unsigned int size)
{
      unsigned int pos=0,count=0,len=strlen(s2);
      char buffer[128]; // long enough for a single word, if not, not safe!
      while(pos < len)
      {
            while(isspace( *(s2+pos)) && pos < len)
                  pos ++;      // go through space
            
            if(pos < len)
            {
                  sscanf(s2+pos, "%s", buffer);
                  int l = strlen(buffer); //
                  word[count] = new char [l+1];  // initialise new array,
                  strcpy(word[count],buffer);
                  count ++;
                  if(count > size-1) return count; // full

                  pos += l;
                  
            }
      }
      return count; // return number of words
}

Thanks for any help given.  
jayb_1979Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

waysideCommented:
    a = s2.length();
     cout << a << endl;
     
//************************************************

     for (int i=0; i<=a; i++)   <----------------------------------------------------------- 1
     {
     cout << word[i] << endl;       //this works
     }

     //for (int i=a; i>=0; i--) <------------------------------------------------------------ 2
     //{
     //cout << word[i] << endl;        //this does not ???
     //}
//************************************************
 
At 1, you are using the number of characters in the string to index the number words. This won't work.

For example, if there were 5 words in a 30 character string, the word[] array will will have 5 elements but you are trying to print 30 elements.

Also, because arrays use a zero-based index, the termination should be <, not <=.

And to get them to print on one line, don't do <<endl after each string:

     for (int i=0; i<n1; i++)   // n1 returned by wordCount
     {
       cout << word[i] << " ";
     }
     count << endl;

To go down from the top, you have to start i at n1-1, again because of the zero-based indexing:

    for (int i=n1-1; i>=0; i--)   // n1 returned by wordCount
     {
       cout << word[i] << " ";
     }
     count << endl;

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jayb_1979Author Commented:

Thanks,

am getting these errors though so i guess im doing something stupid, (after have inserted ur code),
Thanks for the expalnation.  Sorry, I know I have probably done something stupid.





ocuments and settings\berrimanj\my documents\visual studio 2005\projects\rev1\rev1\rev1.cpp(33) : warning C4996: 'getche' was declared deprecated
1>        c:\program files\microsoft visual studio 8\vc\include\conio.h(146) : see declaration of 'getche'
1>        Message: 'The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getche. See online help for details.'
1>c:\documents and settings\berrimanj\my documents\visual studio 2005\projects\rev1\rev1\rev1.cpp(49) : warning C4267: '=' : conversion from 'size_t' to 'int', possible loss of data
1>c:\documents and settings\berrimanj\my documents\visual studio 2005\projects\rev1\rev1\rev1.cpp(58) : error C2065: 'count' : undeclared identifier
1>c:\documents and settings\berrimanj\my documents\visual studio 2005\projects\rev1\rev1\rev1.cpp(58) : error C2563: mismatch in formal parameter list
1>c:\documents and settings\berrimanj\my documents\visual studio 2005\projects\rev1\rev1\rev1.cpp(58) : error C2568: '<<' : unable to resolve function overload
1>        c:\program files\microsoft visual studio 8\vc\include\ostream(971): could be 'std::basic_ostream<_Elem,_Traits> &std::endl(std::basic_ostream<_Elem,_Traits> &)'
1>        with
1>        [
1>            _Elem=wchar_t,
1>            _Traits=std::char_traits<wchar_t>
1>        ]
1>        c:\program files\microsoft visual studio 8\vc\include\ostream(963): or 'std::basic_ostream<_Elem,_Traits> &std::endl(std::basic_ostream<_Elem,_Traits> &)'
1>        with
1>        [
1>            _Elem=char,
1>            _Traits=std::char_traits<char>
1>        ]
1>        c:\program files\microsoft visual studio 8\vc\include\ostream(937): or 'std::basic_ostream<_Elem,_Traits> &std::endl(std::basic_ostream<_Elem,_Traits> &)'
1>c:\documents and settings\berrimanj\my documents\visual studio 2005\projects\rev1\rev1\rev1.cpp(65) : error C2563: mismatch in formal parameter list
1>c:\documents and settings\berrimanj\my documents\visual studio 2005\projects\rev1\rev1\rev1.cpp(65) : error C2568: '<<' : unable to resolve function overload
1>        c:\program files\microsoft visual studio 8\vc\include\ostream(971): could be 'std::basic_ostream<_Elem,_Traits> &std::endl(std::basic_ostream<_Elem,_Traits> &)'
1>        with
1>        [
1>            _Elem=wchar_t,
1>            _Traits=std::char_traits<wchar_t>
1>        ]
1>        c:\program files\microsoft visual studio 8\vc\include\ostream(963): or 'std::basic_ostream<_Elem,_Traits> &std::endl(std::basic_ostream<_Elem,_Traits> &)'
1>        with
1>        [
1>            _Elem=char,
1>            _Traits=std::char_traits<char>
1>        ]
1>        c:\program files\microsoft visual studio 8\vc\include\ostream(937): or 'std::basic_ostream<_Elem,_Traits> &std::endl(std::basic_ostream<_Elem,_Traits> &)'
1>c:\documents and settings\berrimanj\my documents\visual studio 2005\projects\rev1\rev1\rev1.cpp(83) : warning C4267: 'initializing' : conversion from 'size_t' to 'unsigned int', possible loss of data
1>c:\documents and settings\berrimanj\my documents\visual studio 2005\projects\rev1\rev1\rev1.cpp(100) : warning C4267: 'initializing' : conversion from 'size_t' to 'unsigned int', possible loss of data
1>c:\documents and settings\berrimanj\my documents\visual studio 2005\projects\rev1\rev1\rev1.cpp(110) : warning C4267: 'initializing' : conversion from 'size_t' to 'int', possible loss of data
1>Build log was saved at "file://c:\Documents and Settings\berrimanj\My Documents\Visual Studio 2005\Projects\rev1\rev1\Debug\BuildLog.htm"
1>rev1 - 5 error(s), 5 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-d
jayb_1979Author Commented:


Got it working,  

have commented out     count << endl;  to do this,  what do these lines do,  (Is it spelling mistake)?

Thanks your help is greatly recieved
Build an E-Commerce Site with Angular 5

Learn how to build an E-Commerce site with Angular 5, a JavaScript framework used by developers to build web, desktop, and mobile applications.

waysideCommented:
    count << endl;

Oops! that was a type on my part. It should have been

     cout << endl;

endl writes the newline character to the output, which makes the output go to the next line.

When you had it in your loop, this is why each word was printed on a separate line:

     cout << word[i] << endl;  

I moved printing the newline to outside the loop to that all the strings would appear on one line, but I fat-fingered it. :)
jayb_1979Author Commented:
Thanks really appreciated. Am a total newbie and that just got my first (id like to think) half decent program working,

great start to the weekend

thanks again
waysideCommented:
Glad I could help!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.