There are a lot of problems with your code.
You are not allocating any memory for cin.getline()
to read into. const char* name;
is declaring an uninitialized pointer to nothing. You have to allocate memory for name
before you can then read any data into it.
cin.getline()
expects two input parameters (a pointer to an allocated buffer, and the max number of characters the buffer can hold), but you are only passing in one value.
You are calling strlen()
before you have read anything into name
(and there is a syntax error on your strlen()
statement anyway).
You are passing a
to std::cout
using >>
, but std::ostream
does not implement the >>
operator. You have to use <<
instead.
And lastly, don't use using namespace std;
.
Try this instead:
#include <iostream>
#include <cstring>
int main()
{
//writing your name, and counting the characters including \0
int a;
char name[32];
std::cin.getline(name, 32);
a = std::strlen(name);
std::cout << "You entered: " << name << std::endl;
std::cout << "It is << a << " chars in length" << std::endl;
return 0;
}
Or, if you really don't like using std::
everywhere, at least use using <identifier>;
instead of using namespace std;
:
#include <iostream>
#include <cstring>
using std::cin;
using std::strlen;
using std::cout;
using std::endl;
int main()
{
//writing your name, and counting the characters including \0
int a;
char name[32];
cin.getline(name, 32);
a = strlen(name);
cout << "You entered: " << name << endl;
cout << "It is " << a << " chars in length" << endl;
return 0;
}
Now, that being said, the preferred solution is to use std::getline()
instead of cin.getline()
:
#include <iostream>
#include <string>
int main()
{
int a;
std::string name;
std::getline(std::cin, name);
a = name.length();
std::cout << "You entered: " << name << std::endl;
std::cout << "It is " << a << " chars in length" << std::endl;
return 0;
}