HELLO THIS IS MY FIRST POST.

I WISHED IF ANY ONE COULD HELP IN EXTRACTING WORDS FROM A CHAR ARRAY -STRING

LIKE IF THE SENTENCE INPUTTED BY USER - JACK WENT UP
THEN I NEED TO PRINT THESE WORDS SEPARATELY ON FRESH LINES
OUTPUT-
JACK
WENT
UP


I TRIED THIS BUT THIS IS NOT WORKING

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
char a[100];
int x;
cout<<" enter a sentence";
gets(a);
for(int x=0;a[x]!='\0';x++)
{  
  if(a[x]==' ')
{  
  for(int p=0;p<=x;p++)
   cout<<a[p];

  cout<<endl; }
}
}

the output produced is

JACK
JACK WENT
JACK WENT UP

JUST ONE MORE REQUEST
THE PROGRAM SHOULD BE DONE ONLY BY SIMPLE CHAR TYPE ARRAYS PLEASE.

I HAVE TRIED THIS QUERY ON OTHER FORUMS BUT ALL ADVICED TO USE "STDL "STRINGS WHICH IS NOT IN MY COURSE.

YOU CAN USE MULTIDIMENSIONAL ARRAYS FOR STORING WORDS

HOPING FOR A SOLUTION

Your output is wrong because you're starting the inner for loop at 0 every time.So when a[x] == ' ' it's writing start point to ' '.

You should save the ' ' character's index in a variable and start the loop at this variable.

Finally there is not a ' ' character at the sentence's and so you should repeat the inner for once again outside the first loop(i.e,before return 0).

#include<iostream>
using namespace std;

int main(){
    
char a[100];
int x,m = 0,p;

cout<<"Enter a sentence"<<endl;
gets(a);

for(x=0;a[x]!='\0';x++)
{
        if(a[x]== ' ')
        {
                   for(p=m;p <= x;p++)
                           cout<<a[p];
                   m = x + 1;//For not writing the space character at the //word's lead.You may do m = x;
        }

cout<<endl; 
}

for(p = m; p <= x;p++)
     cout<<a[p];

return 0;

}

And note that "gets()" function is dangereous .Try to fgets() instead.

Thank you so much for the wonderful solution .
I had been trying so hard to get the correct solution ,THANKS A LOT.

But I have 1 query-
Why gets() is dangerous ,what and how do we use fgets ,I mean is there a special prototype?

I mean You're welcome...:D:D:D

I am not good at strings . So please could you help me in getting this question right?

The question is -if the user inputted -' 'JACK WENT UP' '
then the output should be -

UP WENT JACK

I tried to reverse the string from the last space position but that is not working but cant get the second last index having a space .

Please please help!!

Please ,the solution must only include functions related to char type strings or otherwise I will not be able to comprehend .

Well my sir told to transfer the words separately in to the rows of a 2 dimensional array and then print them accordingly,but I am unable to get the hang of it.

Please help.

Post your latest code so that it would be easier for someone to help you out.

iI cant get the hang of it

the code is the same as above

#include<iostream>
using namespace std;

int main(){

    char a[100];
    int x,m = 0,p;

    cout<<"Enter a sentence"<<endl;
    gets(a);

    for(x=0;a[x]!='\0';x++)
    {
        if(a[x]== ' ')
        {
                   for(p=m;p <= x;p++)
                           cout<<a[p];
                   m = x + 1;//For not writing the space character at the //word's end.
        }

        cout<<endl; 
    }

    for(p = m; p <= x;p++)
         cout<<a[p];
     cout<<m<<"last space charecter";              

    for(int r=m;r>=m;r--)
      cout<<a[p];


}

The word order needs to be reversed .(I know want to know how do we get the space positions from end to beginning.)

FOR EXAMPLE-

if you had -' 'JACK WENT UP' '
0-' '
1-J
2-A
3-C
4-K
5-' '
6-W
7-E
8-N
9-T
10-' '
11-U
12-P
13-' '

I want to print words this way

                                        from 10 position to 13 position
                                        from 5 position to 10 position 
                                        from 0 position to 5 position

I have tried a lot but not got it correct
Please help me in this !!!

the below will reverse your sentence it works.

#include<iostream>
using namespace std;

int main(){
    char a[100];
    char b[10][20];
    int x,m = 0,p,wrd = 0, i = 0;
    
    cout<<"Enter a sentence"<<endl;
    gets(a);
    
    for(x=0; a[x] != '\0'; x++) {
        if(a[x] == ' ') {
            for(p=m;p <= x;p++) 
                b[wrd][i++] = a[p];
            b[wrd][i] = '\0';
            m = x + 1;
            wrd++;
            i = 0;
        }
    }
    i=0;
   if(a[x] == '\0')
       for(p=m;p <= x;p++) 
            b[wrd][i++] = a[p];
        b[wrd][i] = '\0';
        
    for(i=wrd; i >= 0 ; i--) {
        int j = 0;
        while( b[i][j] != '\0')
            cout << b[i][j++];
        cout << endl;
    }
}

The first loop of for -understood
but from ---

i=o

i cant understand

if(a[x]==' ')
.
.
.
end

please give a few statements regarding these lines I am unable to get it. the 2-d array is used to tranfser words separately into it

but after that unable to get it specially b[j]==' '
because this array is containg words only right now in for loop

this part is because after the "up" there is no space
check for "\0"
we store a new word "up" in b[2][0]... or second row of
b[10x20] array.
here wrd=2 and i=0,1,2.. that is 0=u, 1=p, 2='\0'

i=0;
   if(a[x] == '\0')
       for(p=m;p <= x;p++) 
            b[wrd][i++] = a[p];
        b[wrd][i] = '\0';

here b[j] is just that i = wrd and j is the stings
jack
went
up
where b[2][0] = u
b[1][0] = w
b[0][0] = j


for(i=wrd; i >= 0 ; i--) {
        int j = 0;
        while( b[i][j] != '\0')
            cout << b[i][j++];
        cout << endl;
    }

hope you get the idea. just throw in some cout statments in the
code and print b[j] you will get it.

commented: Nice +21

Thank you very much. The solution was great.I understood!!!!!

Member Avatar for iamthwee

the below will reverse your sentence it works.

#include<iostream>
using namespace std;

int main(){
    char a[100];
    char b[10][20];
    int x,m = 0,p,wrd = 0, i = 0;
    
    cout<<"Enter a sentence"<<endl;
    gets(a);
    
    for(x=0; a[x] != '\0'; x++) {
        if(a[x] == ' ') {
            for(p=m;p <= x;p++) 
                b[wrd][i++] = a[p];
            b[wrd][i] = '\0';
            m = x + 1;
            wrd++;
            i = 0;
        }
    }
    i=0;
   if(a[x] == '\0')
       for(p=m;p <= x;p++) 
            b[wrd][i++] = a[p];
        b[wrd][i] = '\0';
        
    for(i=wrd; i >= 0 ; i--) {
        int j = 0;
        while( b[i][j] != '\0')
            cout << b[i][j++];
        cout << endl;
    }
}

IMO it would have been better to have left her to her own devices to come up with a solution, instead of writing the entire code. All she needs was a few helping hints.

Also, why use an example with gets(). Show her what she should use...
http://www.daniweb.com/tutorials/tutorial45806.html or even cin.getline?

>IMO it would have been better to have left her to her own devices to
>come up with a solution, instead of writing the entire code.
True, but in this case...not so much of an issue. That solution is rather poorly implemented and overly complex. If you're going to use a multidimensional array, the problem is trivial and takes practically no thought at all:

#include <iostream>

using namespace std;

int main()
{
  char words[10][100];
  int i = 0;

  cout<<"Enter a sentence: ";

  while ( i < 10 && cin>> words[i] )
    ++i;

  while ( --i >= 0 )
    cout<< words[i] <<' ';
  cout<<'\n';
}

The real problem is when you have to do the reversal in-place. Even then, I could still do it with less complexity than pengwn managed to put into the simpler solution. :icon_rolleyes:

True, but in this case...not so much of an issue. That solution is rather poorly implemented and overly complex. If you're going to use a multidimensional array, the problem is trivial and takes practically no thought at all:

#include <iostream>

using namespace std;

int main()
{
  char words[10][100];
  int i = 0;

  cout<<"Enter a sentence: ";

  while ( i < 10 && cin>> words[i] )
    ++i;

  while ( --i >= 0 )
    cout<< words[i] <<' ';
  cout<<'\n';
}

Thanks a lot for such a precise solution .
But i am a little confused about 2 things

-can we really treat char arrays as integers and use cin>>words[i] (char type)

int a;
like cin>>a

-Secondly if words[10][100] is a 2-d array then can we really use as a single dimensional array like you have used in

cout<<words[i]

Please help !!!

I TRIED YOUR SOLUTION AND IT IS WORKING WELL .

I again got it but this time very easily .Your solution was very accurate,
but in this case we will have to give the no. of strings entered initially like you have given it 10

same way should it be
int n;
cin>>n;
words[n][100];

By the way could you tell me how do we daclare char arrays of "n-size".Its dynamic allocation right?

>-can we really treat char arrays as integers and use cin>>words (char type)
You can use cin's >> operator with any data type that overloads that operator. That means all of the built-in types and any custom types that support the operator. So yes, you can use cin's >> operator to read a C-style string. However, while I kept my example simple, to be strictly correct with an array of char you should take care to restrict the field width so that the array isn't overfilled:

#include <iomanip>

...

while ( i < 10 && cin>> setw ( 100 ) >> words[i] )

I say that because I can see you using this instead of getline to read strings, and/or not using the C++ string type for a while.

>-Secondly if words[10][100] is a 2-d array then can we really use as a single dimensional array
A two dimensional array is really just an array of arrays. If you index the first dimension, you get a one dimensional array and can use it as a one dimensional array.

>same way should it be
>int n;
>cin>>n;
>words[n][100];
No, C++ doesn't support non-constant array sizes, so you can't declare an array with user input. However, you can simulate an array using pointers. Most of the time you'll want to do this with both dimensions, but it's actually easier (though a tad more obscure) to do it only with the first dimension:

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
  const int size = 100;
  int n;

  cout<<"Number of words: ";

  if ( cin>> n ) {
    char (*words)[size] = new char[n][size];

    cout<<"Enter a sentence: ";

    int i = 0;

    while ( i < n && cin>> setw ( size ) >> words[i] )
      ++i;

    while ( --i >= 0 )
      cout<< words[i] <<' ';
    cout<<'\n';

    // Always release what you allocate
    delete[] words;
  }
}

>By the way could you tell me how do we daclare char arrays of
>"n-size".Its dynamic allocation right?
Yes. It goes like this:

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
  // Use the new[n] operator to
  // allocate memory to a pointer
  char *p = new char[100];

  // Use it pretty much like an array
  if ( cin.getline ( p, 100 ) )
    cout<<">"<< p <<"<\n";

  // Use the delete[] operator to
  // release memory allocated with new[n]
  delete[] p;
}

Thank you a lot for the timely help.You have cleared the biggest doubt regarding C++ strings.
But here I request you to tell me

if ( cin>> n ) {
char (*words) = new char[n];


My professor has not taught about pointers for that is not in course but I
think to learn it .
Please could you explain this line to me as it as poniters.
I know one thing that pointers indicate to a value but after that no clue.
Please do not be irritated.I am trying to understand.I assume that is just the syntax.
right? But this for 2-d array of char type but on Left you have used 1-d char array

I think you are again using 2 D array as 1D array

Similarly it will be
int n;
int *a[100]=new[n];(for integer types)

char*wd=new[n];(for 1-d char array)

while(i<n && cin>>setw(100)>>words;


Besides what is meant by overfilling of the array that you use setw() here.
I have beentold that it is used to specify minimum no. of charecter positions on the output field
a varaible will consume.

PLEASE PERTAIN TO ONLY C++ FOR THATS IN MY SYLLABUS

>I know one thing that pointers indicate to a value but after that no clue.
This should clear up several things about pointers.

>but on Left you have used 1-d char array
But it's not. It's a pointer to a one dimensional array. In this case you can think of it as a two dimensional array where the first dimension is set dynamically.

>I think you are again using 2 D array as 1D array
No, I'm using a one dimensional array as a one dimensional array. A two dimensional array is an array of arrays. If you declare ma as a two dimensional array, ma[0] is a one dimensional array.

>Besides what is meant by overfilling of the array that you use setw() here.
You need to tell cin when to stop. If you don't, it'll stop when it reaches whitespace. But what happens if the input stream contains 50000 characters with no whitespace? Well, cin will try to write all 50000 characters to your array. If your array can only hold 100 characters, that's a really bad thing.

By input stream you refer to Array and whitespace-blank?
Or it is the same stream which we use in file operations.
I generally deal with arrays of char size-100.For this means that it will store upto 100 charecters .Right?

Thank you ,I am reading about poniters
by the link you send

You are really nice in explainations

>By input stream you refer to Array and whitespace-blank?
cin is an input stream. cout is an output stream.

>For this means that it will store upto 100 charecters .Right?
If it's just an array, yes. If it's a string, it will store up to 99 characters and always leave room for the '\0' terminator at the end of every C-style string.

Very well.I am getting it. With the link I would be able to understand about syntax for creation of n sized 1D,2D ARRAYS of char and int type for that is one thing that I cant understand at all and learn.

By the way I want to make sure that concept of and use of pointers is same in both Cand C++
for i am restricted to C++

Thank you for taking up so much pains .I will not tax you more for now.Even my college cant explain as well as you do.Thank you once again

>By the way I want to make sure that concept of and use of pointers is
>same in both Cand C++ for i am restricted to C++
I can't think of any glaring differences that you'll encounter. For the most part, what you learn in C can be applied to C++.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.