C-String Arrays

U

Usenet Text

I am a C++ newbie and am a little confused on CString arrays. I wrote an
example below of what I am trying to do below. It seems that if I enter in a
model number like A123 or B345, that when the cout statement comes around
that it only outputs the first character. Is there no way to do this with
type char and have the cout output the entire 4 character model number? If
not would the only choice be a type string? I want to do an input validation
on each character (isdigit, isalpha and strlen) so that is why I am trying
to make it a char type. Thanks for any input :).

#include <iostream>
using namespace std;

char modelNum[4];

int main ()
{
for (int index = 0; index < 4; index++)
{
cout << "Please enter a model number " << endl;
cin >> modelNum[index];
cin.ignore(4);
}

for (int IDX = 0; IDX < 4; IDX++)
{
cout << modelNum[IDX] << endl;
}

return 0;
}
 
P

Phlip

Usenet said:
I am a C++ newbie and am a little confused on CString arrays. I wrote an
char modelNum[4];

That is not a string array - it is an array of characters, which are
individual letters or symbols.

char modelNum[4] = { 'y', 'o', '\0' };
cout << modelNum << endl

That will print "yo" to the console.

This is an array of strings:

std::string modelNum[4];

You must return to your textbooks (plural!) before attempting to code again.
It's not as easy as just replacing 'char' with 'string'...
 
R

Rolf Magnus

Usenet said:
I am a C++ newbie and am a little confused on CString arrays. I wrote
an example below of what I am trying to do below. It seems that if I
enter in a model number like A123 or B345, that when the cout
statement comes around that it only outputs the first character.

It prints the character you specify. You have an array of 4 char, and in
your first for loop, you let the user enter the character for each of
those 4 and ignore the rest. Later, you print those four characters.
Is there no way to do this with type char and have the cout output the
entire 4 character model number?

Not with char, no. A char can hold exactly one character. You can use
arrays of char for holding more than one, but I'd recommend
std::string.
If not would the only choice be a type string?

If you mean std::string, then no, it's not the only choice, but it's
probably the best choice.
I want to do an input validation on each character (isdigit, isalpha
and strlen) so that is why I am trying to make it a char type.

And? What stops you from using them with std::string?
 

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

Forum statistics

Threads
474,170
Messages
2,570,924
Members
47,464
Latest member
Bobbylenly

Latest Threads

Top