Array's

I am writing a program using an Array called words, when the user enters the word "END" the Array should output all the words pryor to that but for some reason all I get is the word "END" one time. Can anyone help me with this?

#include <iostream>

using namespace std;

int main( )
{

//Drill 4.
cout<<"THIS IS DRILL 4 "<< endl;
const int SIZE=3;
string words[SIZE];
string END;

for(int i=0;i<SIZE;i++)
{
cout<<"Enter a list of words: "<< endl;
cin>>words[i];
if(words[i]== END)
{
cout<<words[i]<<", ";
}
}
return 0;
}
Last edited on
We'd have to see the relevant code if you want pointers on what you are doing wrong but I'm guessing you want something like this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
using namespace std;

int main()
{
	string Words[100];
	int i;

	for (i = 0 ; i < 100; i++)
	{
		cin >> Words[i];
		if (Words[i] == "END") break;
	}

	for (int j = 0; j <= i; j++)
	{
		cout << Words[j] << " ";
	}

	return 0;
}


This method's a little more advanced, but also a little better:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
	string input;
	vector <string> Words; // You don't need to pre-define the array-size.

	while(input != "END")
	{
		cin >> input;
		Words.push_back(input);
	}

	for (vector<string>::iterator it = Words.begin(); it < Words.end(); it++)
		cout << *it << " ";

	return 0;
}


Edit: Added vector method too.
Note the original post didn't have code. My response to the code is below.
Last edited on
Ah ha! There is your problem.

You made a string called END. However no data was set, so the string is blank. Use this string END = "END"; to set END to the value you were expecting.

You'll notice some different behavior now, but it isn't right just yet.

Take the cout out of the for loop and place it later in the program. Get all of your inputs before dealing with the outputs. It helps you to segment your code. Find a way to "break" out of the for loop imidiately when the "END" string is entered. What could you use? How about break?

Anyways, my code above should help you from there.
Topic archived. No new replies allowed.