Am I crazy?

So I was reading the boards one day and I saw a helpful tip when dealing with cstrings

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;

int main()
{
	char* cstring;
	getline.cin(cstring = new char);
	cout << cstring;


	return 0;
}

I thought it was the coolest thing and saved it in my notes knowing i'd use it again for a lab. Well now that time has come and for some reason both compilers i've tried give me this error "'std::getline' does not have class type". Which is crazy because literally a week ago it worked perfectly fine, i remember because i was geeking out about it. Anyone know why i can't do it now?

You have a few mistakes.

The C programming doesn't really have a string type. The C standard library, with a bit of the language itself, provides a string implementation. The string is stored in an array of char, with a NULL at the end. But you provide the data and the C standard library provides the methods.

So, you need to declare an array large enough for your expected string, something like:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

int main()
{
    char str[32];

    std::cin.getline(str, 32);  // or more correctly cin.getline(str, sizeof(str));
    std::cout << str << std::endl;

    return 0;
}

But in C++, don't use them, they're error prone and must be used carefully. Use the C++ standard string class instead. The example becomes:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>

int main()
{
    std::string str;

    std::getline(std::cin, str);
    std::cout << str << std::endl;

    return 0;
}
Hey kbw, thanks for the reply! I understand your code but the reason I'm asking for help is because I don't want to write the code like you posted, only because the user is asked to enter a name and I'm not supposed to predetermine the size of the cstring. The way I showed the Pointer is automatically pointing to a dynamically allocated array that's the size of the name. Do you perhaps know of another way?
it's cin.getline?
Nah it'll just give me a even worse syntax error
I know i could just declare them all in the structure definition but i've seen this work, i've done it, i just don't know why it's not working. I think i'm am going crazy
> I'm not supposed to predetermine the size of the cstring.
> automatically pointing to a dynamically allocated array that's the size of the name
use `std::string'
Thanks naraku, definitely found my backup plan. Ne i'm not sure what you're trying to say.
Topic archived. No new replies allowed.