954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Copying words into an array of char ?!?

Hello ladies and gents,

I'm trying to copy two words, for instance test and word into an array of characters and have this:

#include <iostream>

int main()
{
	char word[10]= "";
	char *wordArr[10];

	for(size_t i = 0; i < 2; i++)
	{
		std::cin >> word;
		*(wordArr + i)  = word;
	}

	for(size_t i = 0; i < 2; i++)
		std::cout << wordArr[i] << '\n';

	std::cin.ignore(2);
	
	return 0;
}


Thing is, it prints the last word twice as if it doesn't store the first word, what am I doing wrong, can anyone point me in the right direction?

I know I could use strings or even a vector, but, my idea is to work out a version using characters first, then strings and then a vector.

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 

Well, found a solution like this:

#include <iostream>

int main()
{
	char word[10]= "";
	char wordArr[10][10];

	for(size_t i = 0; i < 2; i++)
	{
		size_t j;
		std::cin >> word;
		for(j = 0; j < strlen(word); j++)
			wordArr[i][j] = word[j];
		wordArr[i][j] = '\0';
	}

	for(size_t i = 0; i < 2; i++)
	{
		for(size_t j = 0; j < strlen(wordArr[i]); j++)
			std::cout << wordArr[i][j];
		std::cout << '\n';
	}

	std::cin.ignore(2);
	
	return 0;
}


But, there has to be a way of using char *wordArr[10]; right?

It would make it easier since the use of a pointer to an array of char's wouldn't need to be terminated by yourself, the compiler would do this like Ancient Dragon said in another thread right.

Does any of you guys know how I could use that type of definition in my program?

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 

Hope something in here meets your needs and helps you understand the syntax.

char * wordArr[10];

means wordArr is an array of 10 char pointers, not that wordArray is a pointer to 10 char arrays.

char * word = new char[10];

means word is a pointer to a char array that can contain up to 10 char.

Now, an example of putting words into array directly. without need for user termination

#include <iostream>
using namespace std;

int main()
{
   char word[10]= "";
   char wordArr[10][10];
   int i;

   for(i = 0; i < 10; ++i)
       cin >> wordArr[i];
  
   for(i = 0; i < 10; ++i)
       cout << wordArr[i] << endl;
   
   cin.get();
}

Inputting words into an array indirectly

#include <iostream>
using namespace std;

int main()
{
    char word[10] = "";
    char wordArr[10][10];
    int i;

    for(i = 0; i < 10; ++i)
    {
        cin >> word;
        strcpy(wordArr[i], word);
    }

    for(i = 0; i < 10; ++i)
        cout << wordArr[i] << endl;

    cin.get();
}

Using pointer to pointer to char instead of array of char arrays

#include <iostream>
using namespace std;

int main()
{
   char  **wordArr;
   int i, j, k;
   cin >> i;
   cin >> j;
   wordArr = new char*[i];
   for( j = 0; j < i; ++i)
     wordArr[i] = new char[j];
   
   for(j = 0; j < i; ++j)
      cin >> wordArr[j];

   for(j = 0; j < i; ++j)
      cout >> wordArr[j] << endl;
   
   for(j = 0; j < i; ++j)
      delete[] wordArr[i];
  
   delete wordArr;
    cin.get();
}

Using array of char pointers instead of pointer to pointer to char

#include<iostream>
using namespace std;

int main()
{
   char *wordArr[10];
   int i, j;
   cin >> j;

   for(i = 0; i < 10; ++i)
      wordArr[i] = new char[j];
   
   for(i = 0; i < 10; ++i)
      cin >> wordArr[i];

   for (i = 0; i < 10; ++i)
      cout << wordArr[i] << endl;

   for(i = 0; i < 10; ++i)
       delete[] wordArr[i];
   
   cin.get()
}

Another version using array of char pointers:

#include <iostream>
using namespace std;

int main()
{
   char * wordArr[2] = { {"Hello"}, {"World"} };
   cout << wordArr[0] << ' ' << wordArr[1] << endl;

   cin.get()
}
Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396
 

Thanks for those examples Lerner. The reason I came up with my first example code was because the exercise tells you not to store two identical words, therefore I used two variables char word[10]= ""; and char wordArr[10][10]; . That way, I can compare when entering a new word with the already added words to check whether it's not in the list.

I should've written the exercise out, but, I wanted to take this one in small parts as you guys always tell forumers to do, so they don't get overwhelmed with the code. Sorry for that. Anyway, the exercise goes as follows:

- Read a sequence of words from input. UseQuit as a word that therminates input. Print the words in the order they were entered. Don't print a word twice. Modify the program to sort the words before printing them.

I'll be back next week-end, don't have the time to do the exercise now, anyway, thanks again for the thourough explanatioin and examples :!:

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 

Hey Lerner,

Finally got time to work on this exercise again, but, before I do, I'd like to ask whether this way of adding a word into another array is good or not. If not, what are the reasons this is not ideal?

for(size_t i = 0; i < 2; i++)
	{
		size_t j;
		std::cin >> word;
		for(j = 0; j < strlen(word); j++)
			wordArr[i][j] = word[j];
		wordArr[i][j] = '\0';
	}


The intention here was just two add two words into the array to try out. Was I correct that I had to add the '\0' to the end of the word so that it would be correctly terminated?

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 

Hi guys,

Was wondering if any of you could help me out, I'm trying to print the words only once, but, it seems I'm doing something wrong, could someone point me in the right direction?

#include <iostream>
#include <cstring>

int main()
{
	char wordArr[5][10];
	short contr;

	for(size_t i = 0; i < 5; i++)
		std::cin >> wordArr[i];

	for(size_t i = 0; i < 5; i++)
	{
			contr = strcmp(wordArr[i], wordArr[i+1]);
			
			if (contr != 0)
				std::cout << wordArr[i] << '\n';
	}

	std::cin.ignore(2);
	
	return 0;
}
JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 

Why ain't you using std::strings?

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

Just wanted to tell you that sometimes your description is rather vague. Always post a question in such way that the person reading it doesn't have to use a compiler to test it out what is going wrong.

If your program displays something and takes some kind of user input, just paste a sample output which is erroneous or not as expected along with what did you expect. This kind of description will help us understanding the problem better.

Now as per your question is concerned, your program only checks to see whether the preceding string is equal to the current string and if it is so then it just skips printing the current string. But your program will fail in conditions where you alternate the words inputted to the program like:

hello
hell
hello
hell
hello

I hope you understand the twist .

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 

>>Was I correct that I had to add the '\0'to the end of the word so that it would be correctly terminated?

No, cin >> automatically null terminates input from either the keyboard or antother stream. The same goes for getline(), which is another way to read in a string.

for(size_t i = 0; i < 5; i++) //for each word in the array
{
   //compare this word with the next word in the array
   contr = strcmp(wordArr[i], wordArr[i+1]);

     //if the two words are not the same
     if (contr != 0)
        //print out current word
        std::cout << wordArr[i] << '\n';
}


You don't want that for two reasons. Number one, when i == 4 you will try to compare wordArr[4] with wordArr[5] but wordArr[5] doesn't exist. If you are lucky your program will crash. If you are unlucky you will get undefined behavior and who knows what will happen, it may even appear to work correctly. Number two, the logic isn't what you want. You want:

bool found = false
for each word in the array //this word
   for each word prior to this word //current word
      if this word is the same as current word
         set found to true
   if not found 
      print out this word
Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396
 
Why ain't you using std::strings?

>> First post "I know I could use strings or even a vector, but, my idea is to work out a version using characters first, then strings and then a vector." ;)Just wanted to tell you that sometimes your description is rather vague. Always post a question in such way that the person reading it doesn't have to use a compiler to test it out what is going wrong.

I'll try my best to explain it more thoroughly next time :!:

@ Lerner, thanks for the explanation.

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 

I GIVE UP !!!!!

Ive been trying to program for over two years now, have been reading several books, did all exercises, but for some unknown reason, I'm not getting it.

So, after some thought about it, Ive decided to stop, I want to thank all of you who have helped me the past two years here on Daniweb and wish you all the best.

Kind regards,
Johan aka JoBe

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 

*sigh* We really will miss you JoBe, though I wish you hadn't given up.

Your friend always,
~s.o.s~

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 

Thanks for the kind words s.o.s, but, I can't stop untill I know the answer, so if someone would please help me out with this, Ive been trying and I can't find the solution.

The code Ive got is this:

#include <iostream>
#include <cstring>

int main()
{
	char wordArr[5][10];
	bool contr = false;
	size_t i, j;

	for(i = 0; i < 5; i++)
		std::cin >> wordArr[i];

	for(i = 0; i < 5; i++)
	{
		for(j = 0; j < i; j++)
		{
			contr = strcmp(wordArr[i], wordArr[j]);
			
			if (contr == true)
				contr = true;
		}
			if (contr == false)
				std::cout << wordArr[i] << '\n';
	}

	std::cin.ignore(2);
	
	return 0;
}


But, if I use the input:
one
two
one
four
five

The output is:
one

What am I doing wrong :confused:

Getting so frustrated by not finding this solution :mad: And it is probably something simple that I can't see !!!!!!

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 
#include <iostream>
#include <cstring>

int main()
{
	char wordArr[5][10];
	bool contr = false;
	size_t i, j;

	for(i = 0; i < 5; i++)
		std::cin >> wordArr[i];

	for(i = 0; i < 5; i++)
	{
		for(j = 0; j < i; j++)
		{
			contr = strcmp(wordArr[i], wordArr[j]);
			// If the above line sets contr to true or false...
			if (contr == true)    // what are these two lines for?
				contr = true;
		}
			if (contr == false)
				std::cout << wordArr[i] << '\n';
	}

	std::cin.ignore(2);
	
	return 0;
}

What is it you are trying to do?

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

Hi Walt,


Well, Lerner posted this helpfull piece of pseudo code:

bool found = false
for each word in the array //this word
   for each word prior to this word //current word
      if this word is the same as current word
         set found to true
   if not found 
      print out this word


And I thought, oh, now I get it:

-First I have a loop for the whole array.
-Then, I have a loop for the word that is being checked whether it exists allready.
-Then, if that word is the same one of the allready added words in the first loop, put the bool variable to true, if not, at the end of looping threw the second loop. Output the word, since it hasn't been added yet.

The idea of the exercise now is to print every word only once, meaning:
one
two
one
four
five

would have to print:
one
two
four
five

Somehow, I'm just not seeing what it is that is wrong with the code Ive written with the help of the pseudo code from Lerner.

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 

Hi Walt,

Well, Lerner posted this helpfull piece of pseudo code:

bool found = false
for each word in the array //this word
   for each word prior to this word //current word
      if this word is the same as current word
         set found to true
   if not found 
      print out this word

And I thought, oh, now I get it:

-First I have a loop for the whole array. -Then, I have a loop for the word that is being checked whether it exists allready. -Then, if that word is the same one of the allready added words in the first loop, put the bool variable to true, if not, at the end of looping threw the second loop. Output the word, since it hasn't been added yet.

The idea of the exercise now is to print every word only once, meaning: one two one four five

would have to print: one two four five

Somehow, I'm just not seeing what it is that is wrong with the code Ive written with the help of the pseudo code from Lerner.

Hint: wouldn't it be a lot easier if you sorted the current words into alphabetical order first.

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 
Hint: wouldn't it be a lot easier if you sorted the current words into alphabetical order first.

Probably, but the exercise goes as follows:

- Read a sequence of words from input. Use Quit as a word that therminates input. Print the words in the order they were entered. Don't print a word twice. Modify the program to sort the words before printing them.

So,
1) Read a sequence of words from input.
2) Use Quit as a word that terminates input.
3) Print the words in the order they were entered.
4) Don't print a word twice.
And
5) Modify the program to sort the words before printing them.

I could try what you suggest, but, then I won't be doing it in the order the exercise says, probably for the reason that N°4 would become easier:?:

Anyway, thanks for the tip iamthwee

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 

>I could try what you suggest, but, then I won't be doing it in the order the exercise says, probably for the reason that N°4 would become easier

It certainly would be a lot easier. Which is how most hash tables operate I would imagine. I.e sorting the list first before removing duplicates.

Of course after sorting you lose the order you begin with.

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 
Somehow, I'm just not seeing what it is that is wrong with the code Ive written with the help of the pseudo code from Lerner.


Okay. Here this goes.

What Mr. Lerner tried to explain is that if you start from the start of the array, you would have a hard time keeping track of duplicates.

Eg. one, two, one, two, three

If you begin at the start of the array you have no way of knowing that the current word under consideration would be repeated or not i.e. if we consider the first word "one" we have no way of knowing that "one" would occur again or not.

The only logical thing to beat this problem would be to start from the end of the array, eg. "three", look up for it in the whole array, and see if it occurs anywhere in the whole array. If it does, don't print "three" because we know for sure that we will encounter "three" again definately.A sample run for input "one, two, one, two, three"

Current Word: three
Searching upwards for "three"...not found
Print "three"

Current word: two
Searching upwards for "two"...found
Dont print "two"

Current word: one
Searching upwards for "one"...found
Dont print "one"

Current word: two
Searching upwards for "two"...not found
Print "two"

Current word: one
Searching upwards for "one"...not found
Print "one"

I won't let you give up so easily ;)

Hope it helped, repost if necessary.

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 

Okay. Here this goes.

What Mr. Lerner tried to explain is that if you start from the start of the array, you would have a hard time keeping track of duplicates.

Ah, ok, let me see whether I can find a solution that way.I won't let you give up so easily ;)

Thanks for sticking in s.o.s :) Programming is sometimes so frustrating, but, I can't seem to let it go, seems like Ive been bitten by the microbe, problem is, my brains don't seem to be willing to help out here. Glad that this is merely a hobby of mine and I don't have to earn a living with it, wouldn't be earning alot with it :cheesy:Hope it helped, repost if necessary.

I most certainly will s.o.s, but, it'll probably will be next week since during the week, I don't have time, full time job and other responcebilities.

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You