| re: Having trouble with char*
Ian Arnold wrote:
[color=blue]
> Alright, so I know that you can use char pointers to store strings,[/color]
You don't use pointers to store strings. You use arrays for storing them and
the pointers to point to the start or any other character of such an array.
char* is _not_ a string type. It's a pointer to a char and nothing else.
[color=blue]
> and I'm trying to make a very simple program to see how it all works that
> will have the user enter 5 characters, then the computer will show
> those five characters back to the user. So far I have:
>
> #include <iostream.h>[/color]
This is an ancient non-standard header. Instead, use:
#include <iostream>
[color=blue]
> int main()
> {
> char* buffer = " "; //Five spaces[/color]
Five spaces (plus a '\0' character) that can _not_ be modified. String
literals are constant, and your pointer points to one.
[color=blue]
> char in;
> char out;
>
> while(in = *buffer++)[/color]
Ok, here, you copy the next character from the string into 'in'.
[color=blue]
> {
> cin >> in;[/color]
Here, you overwrite 'in' again. Then you do nothing with it.
[color=blue]
> }
>
> while(out = *buffer++)
> {
> cout << out;
> }
>
> return 0;
> }
>
> This program works how it is supposed to until it gets to the
> outputing; nothing happens.[/color]
That's not quite right. The five spaces that are still in the string literal
are printed.
[color=blue]
> It gets the five characters, then ends.
> Please help me make this work, and if possible I want it to be based
> off of using the char*, and not an array or just five char variables.[/color]
I suggest you use std::string instead. |