-
Problem using getLine()
I am trying to use getline to read in a string but its not working
Code:
#include <cstdlib>
#include <iostream>
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
char *first, last;
string s;
cout << "Enter your first anames: ";
cin.getline(first,255);
cout << "Your initials are " << first ;
return 0;
}
-
you need to explain exactly in what way it's not working.
that being said, you're not allocating any space for reading data. you can't just declare a pointer and expect to read data into memory at the address that it represents. you need to allocate memory using new.
since you're already using string, although you didn't include the header for it, you should just use std::getline instead of cin.getline. it uses string instead of char pointers, and is much safer and less error prone. use of char pointers for storing text strings is a vestigial feature for compatibility with C, and really should not be used in pure C++ code.
-
It's also (in my opinion) far nicer dealing with string manipulation using the std::string and its functions. Love c++ for this. Once you get used the built in string functions (maybe methods is more appropriate), you will not want to go back.