Getting a string from the user

I’m struggling to find an effective method of getting a string which can include spaces from the user. I’m just writing a program that I .L in a ROOT shell. In any other context I would use getline(cin, s); but as far as I can tell this doesn’t work in cint for whatever reason–at least not the same code I have that works great in gcc.

I have a function I’ve written with brute-force programing that appears to do the job in a somewhat limited sense:

TString funky_getline() { char* a = "a"; TString b; gets(a); b = a; return b; }
However, when I try to use the strings I get from the user this way (as the title for a graph or an axis) cint tends to crash at seemingly random points (it will crash one time when I run the program, but if I open a new shell and try again it won’t, for example). At this point I can’t tell if this is results from some fault of mine (as the code is pretty bad; I just started changing things until I found one that “works”) or what’s going on, but any help would be great.

I’m using ROOT version 4.04/02 and CINT 5.15.169 if that makes any difference.

Your code does not work because you have a memory
overwrite in the gets() call if the user types more than
one character. Check the manpage for details.

Cint should be providing the global getline() function,
but clearly it is not. This will require some investigation
to determine the cause.

Following is a code example which uses the cin.getline()
member function to do what you want. The example
echos what the user types to the screen. I have verified
that this works both with g++ and cint. Please note that
in this example I do not handle the case of the user typing
more than 2048 characters per line, that would require
dynamically allocating memory blocks and chaining them
together, too much work for an example.

[code]#include

using namespace std;

const int BUFSIZE = 2048; // size of our character buffer
static char buf[BUFSIZE]; // buffer to hold typed characters

int main() {
// exit immediately if something
// is really wrong with our standard input
if (!cin.good()) return 1;
// initialize the buffer
buf[0] = ‘\0’;
// clear the io status
cin.clear();
// read a line
cin.getline(buf, BUFSIZE);
// exit on a fatal error
if (cin.bad()) return 1;
// Note: We are not handling the case
// of user input longer than BUFSIZE
// characters.
while (!cin.eof()) {
// print out what we read from the user
cout << buf << endl;
// initialize the buffer
buf[0] = ‘\0’;
// clear the io status
cin.clear();
// read a line
cin.getline(buf, BUFSIZE);
// exit on a fatal error
if (cin.bad()) return 1;
// Note: We are not handling the case
// of user input longer than BUFSIZE
// characters.
}
// possibly handle final line with no newline at end
if (buf[0] != ‘\0’) {
// no newline was read, so do not print one
cout << buf;
}
return 0;
}[/code]

– Paul Russo

Thanks. That works great.