String arrays - newbie

J

john

Hi

I have just started learning C++ and I am working on a a simple
program which stores the days of the week into a char array/s. I will
then use a loop to read from the array/s and display each day of the
week in turn. Then for each day I want to be able to store an integer
value, either using cin or cin.getline.

As yet, I haven't been able to get my string arrays to work!

Any help and assistance would be warmly appreciated.
 
J

Jack Klein

Hi

I have just started learning C++ and I am working on a a simple
program which stores the days of the week into a char array/s. I will
then use a loop to read from the array/s and display each day of the
week in turn. Then for each day I want to be able to store an integer
value, either using cin or cin.getline.

As yet, I haven't been able to get my string arrays to work!

Any help and assistance would be warmly appreciated.

Nobody here can help you get your string arrays to work unless you
show us your code and tell us what is wrong with it.
 
J

Jacques Labuschagne

john said:
Hi

I have just started learning C++ and I am working on a a simple
program which stores the days of the week into a char array/s. I will
then use a loop to read from the array/s and display each day of the
week in turn. Then for each day I want to be able to store an integer
value, either using cin or cin.getline.

As yet, I haven't been able to get my string arrays to work!

Any help and assistance would be warmly appreciated.

Out of curiousity, why don't you learn to use the std::string type
instead?
Either way, post the code you tried and we'll help you out.


Jacques
 
R

Rolf Magnus

john said:
Hi

I have just started learning C++ and I am working on a a simple
program which stores the days of the week into a char array/s. I will
then use a loop to read from the array/s and display each day of the
week in turn. Then for each day I want to be able to store an integer
value, either using cin or cin.getline.

As yet, I haven't been able to get my string arrays to work!

Any help and assistance would be warmly appreciated.

Assistance at what? You haven't shown us any code or even told us what
your problem actually is. "cant' get it to work" is not an appropriate
error description.
 
O

osmium

john said:
I have just started learning C++ and I am working on a a simple
program which stores the days of the week into a char array/s. I will
then use a loop to read from the array/s and display each day of the
week in turn. Then for each day I want to be able to store an integer
value, either using cin or cin.getline.

As yet, I haven't been able to get my string arrays to work!

Back off. Just try to write a program that displays the days of the week.
Forget about the other complicating parts of your ultimate problem.
 
J

Jon Bell

I have just started learning C++ and I am working on a a simple
program which stores the days of the week into a char array/s.

It's usually much easier to use the standard C++ 'string' data type for
storing text data, than to use arrays of char. Also in general, vectors
are easier and safer to use than arrays.

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main ()
{
const int numDays = 7;
vector<string> DaysOfWeek(numDays); // the vector will contain 7 strings
DaysOfWeek[0] = "Sunday";
DaysOfWeek[1] = "Monday";
// you can fill in the rest :)

for (int dayNum = 0; dayNum < numDays; ++dayNum)
{
cout << DaysOfWeek[dayNum] << endl;
}

return 0;
}

Instead of having to keep track of how big the vector is, you can also let
the vector tell you how big it is:

for (int dayNum = 0; dayNum < DaysOfWeek.size(); ++dayNum)
{
// etc.
}

This doesn't make much difference here, but it's a very useful feature in
general, just one of the useful features that vectors have that arrays
don't have.

If your book doesn't say much about vectors and strings, I recommend
Koenig and Moo's "Accelerated C++".
 
F

Fred H

//START:
/*
Dear John

All text in this post is code. Paste it into your favourite editor
and read through it. Then compile it and run it, and read it again :)
Fred H, comp.lang.c++

First have a look at these FAQs:
http://www.parashift.com/c++-faq-lite/containers-and-templates.html#faq-34.1
http://www.parashift.com/c++-faq-lite/containers-and-templates.html#faq-34.2
http://www.parashift.com/c++-faq-lite/containers-and-templates.html#faq-34.3

You can fins a good tutorial on the C++ String class here:
http://cplus.about.com/library/weekly/aa051202a.htm

You should also consider to learn to use STL:
http://cplus.about.com/library/blstl.htm


I'm quite new to C++ myself, but if I was to program something like what
you're describing, I'd go for strings (std::string) in a vector
(std::vector<std::string>).

If you're just doing this to learn about arrays (which I suppose you are),
I guess you'll have to use a two-dimantional array. First you create seven
arrays of chars to hold your days, and then you create an array of pointers
to the seven arrays of chars.

Anyway, here are some examples of what you can do:
*/


#include <iostream>

#include <string>
#include <vector>
#include <algorithm>


using namespace std;


int main() {

/******** ARRAY EXAMPLE ********/
//First ugly way:
//Note how you must specify the length
//one char longer than the name of the day.
//The reason is that you need to declare
//space for the trailing '\0', which is
//automatically added when you
char mon[7] = "Monday";
char tue[8] = "Tuesday";
char wed[10] = "Wednesday";
char thu[9] = "Thursday";
char fri[7] = "Friday";
//You could also specify each element by your self.
//Then you'd have to remember to add '\0' yourself:
char sat[9];
sat[0] = 'S';
sat[1] = 'a';
sat[2] = 't';
sat[3] = 'u';
sat[4] = 'r';
sat[5] = 'd';
sat[6] = 'a';
sat[7] = 'y';
sat[8] = '\0';
//An easier way of doing it would be:
char sun[7] = {'S','u','n','d','a','y','\0'};

//Then you need to put each char array into an array of pointers.
//Remember, an array identifyer, like mon through sun, are pointers:
char *days1[7];
days1[0] = mon;
days1[1] = tue;
days1[2] = wed;
days1[3] = thu;
days1[4] = fri;
days1[5] = sat;
days1[6] = sun;


//A better way of doing it would be to assign all the values
//at once, using the same syntax as we did for sun, only this
//time with strings (array of chars) instead of single chars:
char *days2[7] =
{
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
};

//Now let's have a look at the contents:
cout << "Array Example" << endl;

int i = 0, j = 0; //Variables for counting. Give them defautl values!

//Show contetnt of days1:
cout << "Days (1): ";
for(i = 0; i < 7; i++) {
cout << days1 << " ";
}
cout << endl;

//Show content of days2:
cout << "Days (2): ";
for(i = 0; i < 7; i++) {
cout << days2 << " ";
}
cout << endl;

//If you screw up with dereferencing:
//Showing contetent of first element in each sub array:
cout << "Days (2) screwed up: ";
for(i = 0; i < 7; i++) {
cout << *days2 << " ";
}
cout << endl;

//But ok, lets make things hard. Let's print out each
//end every character one at a time:
cout << "Days (2) one char at a time: ";
for(i = 0; i < 7; i++) {
j = 0;//Remember to reset j.
//Since each of our char arrays is NULL TERMINATED,
//that is, terminated with the NULL, or'\0', character,
//we can use that to loop through each of the sub arrays.
while(days2[j] != '\0') {
cout << days2[j]; //Print single characters:
j++;//This one is REALLY omportant! Otherwise we loop forever!
}
cout << " " << flush;
}

cout << endl << endl;


/******** VECTOR EXAMPLE ********/
//But now that you know how arrays behave, it would
//probably be wise to start using containers. The following
//code is the reason for the inclusion of <string> and <vector>
cout << "Vector Example:" << endl;

//First we make ourself an empty vector that can hold strings.
//This might get your compiler complaining about long class names
//being truncated to 255 characters. For now, just ignore it ;)
vector<string> v1;
//That done, we reserve space for 7 elemets. This is only done to
//prevent later reallocation. You can add as many elements to v1
//as you wish, but if you first reserver space for 7 elements, and
//dont add more than 7, you -know- that it hasn't been reallocated
//in memory. This is important if you use references, pointers and
iterators:
v1.reserve(7);
//another way of reserveing enough space is like this:
vector<string> v2(4);
cout << "Capacity (v1): " << v1.capacity() << endl;
cout << "Capacity (v2): " << v2.capacity() << endl;
//Lets change the capacity of v2 to 7:
v2.reserve(7);
cout << "Capacity (v2): " << v2.capacity() << endl;
//As stated earlier, the capasity does not limit the amount
//of data you can store in v2. That limit is set by physical
//memory. You can find out how many elements you can add to
//v2 by using the max_size method of the vector template class:
cout << "Max size (v2): " << v1.max_size() << endl;

//Before we begin adding elemens, let's have a look at the
//size of v1 and v2:
if(v1.empty()) cout << "Report: v1 is empty." << endl;
else cout << "Report: v1 is not empty." << endl;
if(v2.empty()) cout << "Report: v1 is empty." << endl;
else cout << "Report: v2 is not empty." << endl;
//As you can see, v2 reports that its not empty!
cout << "Report: The size of v1 is " << v1.size() << endl;
cout << "Report: The size of v2 is " << v2.size() << endl;
//Actually, it reports that it has 4 elements! I don't know why
//this is, but it probably has something to do with the reallocation
//taking place when we increased the capasity of v2 from 4 to 7.

//But ok, let's populate the vectors with some data:
v1.push_back("Monday");
v1.push_back("Tuesday");
v1.push_back("Wednesday");
v1.push_back("Friday");
v1.push_back("Thursday");
v1.push_back("Saturday");
v1.push_back("Sunday");

//Now we try and print the contents of the vector:
cout << "Days of the week" << endl;
copy(v1.begin(), v1.end(), ostream_iterator<string>(cout," "));
cout << endl;
//Now, that was all compact code, but what does it mean?
//copy() is a function defines in the std::algorithm class,
//v1.begin() tells copy to start with the first element of
//v1, and v1.end() tells copy to keep going untill it is
//done with the last. The ostream_iterator<string> part
//tells copy that it is supposed to copy what it finds
//between v1.begin() and v1.end() to an outstream, and
//that what it finds is of type string. The outstream is
//specified to be cout, and copy is told to separate each
//string it finds in v1 with a single space.

//As you can see of the output, friday and thursday has
//changed places. This can easily be fixed with another
//function from the algorithm class, swap:
swap(v1[3],v1[4]);
//No let's look at the result:
cout << "Corrected days of the week:" << endl;
copy(v1.begin(), v1.end(), ostream_iterator<string>(cout," "));
cout << endl;

//Ok, this was a short intro to the power given to you by the
//Standard Template Library (STL). If you learn to use it,
//you might find your self writing less error prone code in
//less time than you did before.

return 0;
}//EndOf main()
//END
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,159
Messages
2,570,879
Members
47,417
Latest member
DarrenGaun

Latest Threads

Top