A type..with a number in brackets...

Pages: 12
I thought a [#] meant it was an array with that many keys....
So why is it that when I do
char whatever[5]
and
char whatever
the char whatever doesn't work without the [5] it either throws errors or cut
some of it off...
So what is the difference between
char whatever[5] as a character string and
char whatever[5] as an array?
I am really confused with this?
So three examples:
 
char whatever[5];

 
char whatever;

 
std::string whatever;

So which one is the correct one to use generally for strings...
because I thought whatever[5] was setting an array..however the strcmp function
doesn't work with string, or with char without the number beside it..this is really getting confusing.
Last edited on
When you define an array, the number in the brackets tells how many elements you want.

Once the array is defined, you access each element by puttiing the "index" of the desired elements in the brackets.

Example:

1
2
3
4
5
6
7
8
9
10
int foo[3];  // creates 3 ints

foo[0] = 1;  // set the first of those three
foo[1] = 2;  // set the 2nd of those three
foo[2] = 3;  // set the last of those three

//foo[3] = 4;  // BAD - DON'T DO THIS
       // this steps out of bounds of the array
       //  resulting in memory corruption.
       //  if the array is 3 big, the only [0] - [2] are valid indeces. 
So which one is the correct one to use generally for strings


the last one: std::string whatever

Don't use char arrays for strings until you understand pointers and memory management. std::string makes things much simpler.
Last edited on
That makes sense. So anything you have
char foo[3] it's setting 3 chars?
Also if you do
int foo[3] it's setting 3 ints.

That part makes sense..but when I try to create a variable with just char or just string
I can't use strcmp with it and not to mention it sometimes throws errors...
I tried
std::string foo and I can't use strcmp with it..same with char foo.
In C, strings are implemented as char arrays with the last byte in the string a NUL (0) character.

char hello[] = "Hello, world!";

hello[5] == ","

strlen(hello) == 13

sizeof(hello) == 14 // includes trailing NUL byte.

hello[14] is illegal because we start counting at 0. The valid values are 0..13.

C treats array variables as pointers. Redefining hello as follows:

char* hello = "Hello, world!"

Does that help any?

the rest of the above items still hold.
Alright I just saw your most recent post. I will start doing that, although why is it that..
1
2
3
4
5
6
7
8
9
10
11
    std::cout<<"Would you like to play?  ";
    std::string ask_play;
    std::cin>>ask_play;
    std::cin.ignore();
    std::cout<<std::endl;

    // If not then exit, else we continue the game.
    if (std::strcmp(ask_play, "no") == 0) {
        std::cout<<"we are sorry to see you go.  We hope to see you again sometime soon.";
        exit(1);
    }

That doesn't work.
C:\xampp\htdocs\cpp projects\Police Simulator 1\main.cpp||In function `int main()':|
C:\xampp\htdocs\cpp projects\Police Simulator 1\main.cpp|32|error: cannot convert `std::string' to `const char*' for argument `1' to `int std::strcmp(const char*, const char*)'|
C:\xampp\htdocs\cpp projects\Police Simulator 1\main.cpp||In function `void core_switch(std::string)':|
C:\xampp\htdocs\cpp projects\Police Simulator 1\main.cpp|111|error: switch quantity not an integer|
||=== Build finished: 2 errors, 0 warnings ===|

Which is strange. It doesn't let you do that..unless I set it to char[#].
C style stirngs (char arrays) are a little complicated. Honestly, I would recommend you don't use C style strings until you're much more familiar with the language (and even then I wouldn't recommend it most of the time)

But I suppose I'll whip up a quick explanation.. hold...

EDIT:

There's no need to use strcmp with std::string. strcmp is for C strings.

 
if(ask_play == "no") // <- just do this 
Last edited on
Now I am understanding most of the concepts, but that still makes me wonder what I should use for normal strings..
Should I use that char* whatever;
The problem is even with that it doesn't work with strcmp..based on my reading that was the only way to find out if a string is set to something..basically if they enter "no" I want to exit...otherwise I want to move ahead...and I need to do comparison's a lot, and this is the way I thought all along..kind of confused on that part.

What is the most standard way I should use it across all my code?
Your right..that works.
1
2
3
4
5
6
7
8
9
10
11
    std::cout<<"Would you like to play?  ";
    std::string ask_play;
    std::cin>>ask_play;
    std::cin.ignore();
    std::cout<<std::endl;

    // If not then exit, else we continue the game.
    if (ask_play == "no") {
        std::cout<<"we are sorry to see you go.  We hope to see you again sometime soon.";
        exit(1);
    }

That works perfectly...although you said I should not use c style strings..so how should I do this in general..I want to make sure I am doing this the best way.
but that still makes me wonder what I should use for normal strings..


Use std::string. They're a lot safer, they're sometimes faster, and they're a lot easier to use.

C strings are more "raw". You can represent strings that way, but it requires you to do more work and be more careful.

Should I use that char* whatever;


Generally, no. There are times and places for it, but until you can recognize those times and places, use std::string.

The problem is even with that it doesn't work with strcmp


That's because std::string doesn't work with strcmp. strcmp is for C strings. You don't have any need for strcmp if you're using std::string. Just use the ==, !=, <, >, etc operators to compare strings.

based on my reading that was the only way to find out if a string is set to something


Whatever you're reading is describing C strings, not std::string.


What is the most standard way I should use it across all my code?


std::string
Thank you...that is really helpful. It took me awhile to really understand how all of that was working. So from now on I will use std::string for whatever I am doing and compare it as described. OK that clears up a lot of questions. So generally I will try and avoid char* and char whatever[#].

Now I have one more question which goes back to what I was trying to do now. That explains a lot and I will rewrite my app and start making sure I do this.
So now that I know to use
int whatever when it's an int...
and in that situation I know you can do
int whatever[3] to make an array of 3 ints. I have all of that down...
Now what if I want to make a string array.
Like an array in PHP I would want
1 associated with text, 2 associated with other text..
I wanted like
index[1] = Option 1
index[2] = Option 2
index[3] = Option 3.

Is there a way to do that in C++?
You can do it the same way in C++. There are just 2 things to note:

1) You define the size of the array when you declare the variable
2) Array indeces are zero based, not 1 based. That is, index [0] is the first element in the array... not index [1]


So if you want an array of 3 strings:

1
2
3
4
5
6
7
8
9
10
11
12
std::string mystrings[3];  // make 3 strings

mystrings[0] = "Option 1";
mystrings[1] = "Option 2";
mystrings[2] = "Option 3";

std::cout << mystrings[1]; // print option 2

// what's nice about arrays is that you can use a variable to index them... so...

int index = 2;
std::cout << mystrings[ index ];  // print option 3 


Just make sure that your index is always within the boundaries of the array, or else really, REALLY bad things start happening.
Thank you very much. You have saved me literally weeks worth of hunting and digging up code. I am glad I found this forum, although it seems I am asking a lot of questions I will give back to the community as much as I can by answering people's questions that I know. I had one more (I promise this is the last one for awhile..:)

OK..so the std::string.
I have one problem with it I needed clarified..
before I had this funciton.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*
    Function: centerstring
    Description: Centers text in the user's screen
    Requires: windows.h
*/
void centerstring(char* s) {
    // Get the length of the variable
    int l=strlen(s);
    // Get the current position
    int pos=(int)((80-l)/2);
    // Setup enough padding to make it centered
    for(int i=0;i<pos;i++) {
        std::cout<<" ";
    }
    // send out the variable as well as an endline
    std::cout<<s<<std::endl;
}

I changed it to
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*
    Function: centerstring
    Description: Centers text in the user's screen
    Requires: windows.h
*/
void centerstring(std::string s) {
    // Get the length of the variable
    int l=strlen(s);
    // Get the current position
    int pos=(int)((80-l)/2);
    // Setup enough padding to make it centered
    for(int i=0;i<pos;i++) {
        std::cout<<" ";
    }
    // send out the variable as well as an endline
    std::cout<<s<<std::endl;
}

I just call it with
centerstring("Whatever text here");
This is just an example..I have other functions that had char* whatever as a parameter...and when I change them to std::string they break...any idea why..or how I can convert them over, as I want to do things the right way..and since I got some much advice here you have paved the way for my programming practices for years to come. This will help me have a general style I use throughout all my programs.
Thanks again..
I promise this is the last question for awhile.
Ironically, this is one of the instances where a char array might be more appropriate. Heh. But it's fine to use std::string too. (Using std::string won't hurt, don't worry about it).


remember that strlen, strcat, strcpy, strcmp, etc functions are all meant to work with C strings. If you're using std::string, then you just use string member functions instead.

So insetad of strlen(s), use s.length()

I promise this is the last question for awhile.


Don't worry about it. Feel free to ask whatever. We don't mind helping =)
Perfect. It'll take me awhile to compile all this data. I generally (Especially when using a new language) keep track of all my general information in a database and use that when developing to help me not forget new things..then when they stick heavily in memory I just rewrite them as a general reference or cheat sheet...I really appreciate all of this...it saved me a few months worth of studying the difference.
Now I get it..using C++ built in stuff I get a lot more power than trying to work with C-Style stuff. Should there ever be a situation where I need to use C-Style functions or data types?

Because after looking around a bit..I found this:
http://www.cplusplus.com/reference/string/string/ - Which is a list of all functions I can call for a string..so I can create a string (std::string whatever)..then I can do whatever.functionname() for any of those functions..and a lot of them are really powerful instead of trying to mess with the same thing using Char.

That's not the only situation I ran across.
http://www.cplusplus.com/reference/ - Is that practically a 100% full reference on everything related to C++ built in libraries...so anything in the standard libraries..
which are "iostream" and "string" as well as the container..this is a handy list..as it seems to have them all..except for other third party api's like the windows API or other C++ libraries you might find laying around...this will help a lot.
I am going to (for right now) keep using this post here..because I don't want to flood the forum with my own posts..I had another question that I ran into, and wanted to ask for feedback here without opening another..so I don't waste space. I was trying to rewrite a function that I was provided earlier into a smaller amount...basically I am just creating an array and passing it into a function..and for some reason it compiles right but the entire thing throws a program is not responding windows error...when it goes down to that general area of code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    std::string choices[2];
    choices[0] = "1) Go to the police station.";
    choices[1] = "2) Call the police station.";
    choices[2] = "3) Throw away the mail you got from the police station.";

    option_creator(choices);

    int response = 2;
    switch(response) {
        case 1:
            std::cout<<"go to police station";
            break;
        case 2:
            std::cout<<"call the police station";
            break;
        case 3:
            std::cout<<"With a heavy heart you realize you just are not cut out to be a police officer. You crumble the letter up, roll it up into a"
                     <<" ball and throw it into the garbage.";
            exit(1);
            break;
    }

1
2
3
void option_creator(std::string options[]) {
    std::cout<<"whatever";
}

I cout "whatever" just to see it say something so I know the function is being picked up...but that still isn't working for some reason..it throws an error when it gets around that point in the code. Any advice.
OK, ignore that last one. I figured it out..I wasn't taking enough...the choices had to be set to choices[3] for it to read them all. Now I have one other question.
if I make an array of string elements..is there a way to figure out how many elements are in that array?
Wait..let me ask something different. Is it true that instead of using array's:
1
2
3
std::string whatever[2];
whatever[0]="yes";
whatever[1]="no";

That I should always use vector's instead..I read that somewhere..is that true?

Edit: Sorry I am all over the place..Generally I work with an issue awhile and get stuck and ask a question, and then end up getting lucky and figuring it out.
Last edited on
Pages: 12