Our assignment is to create an array that will hold strings. The problem is that we haven’t gotten to the Strings chapter yet. (We’re on one-dimensional arrays now.) I have searched for hours on different sites (including this one) on how to do an array with strings, but I can’t figure it out.
I need to store four strings of characters in one array, in order to print out the model of four different cars. The cars are input by the user. Here’s my code, which is terribly wrong, as you can see by the output.
I would appreciate any help. I’m a total newbie at programming ... and looking at this program, maybe a total noob!
#include <iostream>
usingnamespace std;
//Function Prototype
void displayArray(char car[], int numberOfElements);
int main()
{
//Declare Array
char carModel[4] = {' '};
//Fill Array
for (int i = 0; i < 4; i += 1)
{
cout << "Enter the model of the car: ";
cin >> carModel[i];
} //end for
//Display the Contents of the Array
displayArray(carModel, 4); //function call
system("pause");
return 0;
} //end of main function
//******Function Definition******
void displayArray(char car[], int numberOfElements) //function header
{
cout << endl << endl;
for (int i = 0; i < numberOfElements; i += 1)
{
cout << "Car Model " << i + 1 << ": " << car[i] << endl;
} //end for
} //end of displayArray function
And here's the goofy output:
Enter the model of the car: Toyota
Enter the model of the car: Enter the model of the car: Enter the model of the
car:
Car Model 1: T
Car Model 2: o
Car Model 3: y
Car Model 4: o
Press any key to continue . . .
I can't figure out how to set the size so each of the four lines will print out the whole name, instead of consecutive letters in only one name.
The only other thing I know is that we're supposed to do it using the char data type.
Thanks for your help. Your code works perfectly. It'll come in handy when we actually get to studying strings. Right now I have to learn how to code it with the char data type (where the strings are strings of characters). I've been scouring more sites, and it looks like I have to have two dimensions to use char -- one for the # of completed strings and one to delimit the length of each string. Do you know how to code it using char?
Thanks again, though, for teaching me about string type arrays!