Getchar?

Feb 5, 2014 at 5:05am
I was trying to make a simple greeting program in which the program asks for a name then outputs "Hello, *name*" but it only prints the first letter of the input name.

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
string name;
string final_greeting;

cout<< "What's your name?";
name = getstring();
cout<< "Hello, ";
cout<< name;
cout<< "\n";

system("PAUSE");
return EXIT_SUCCESS;
}
Feb 5, 2014 at 5:22am
Does that even compile? getstring() isn't a function. You probably want getline, like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string> // use the string header if you are using strings

int main(int argc, char* argv[]) {
    std::string name;

    std::cout << "What's your name? ";
    std::getline(std::cin, name);

    std::cout << "Hello, " << name << "\n";

    // better way of pausing the console
    std::cin.sync();
    std::cin.get();
    return 0;
}
Feb 6, 2014 at 1:56am
No it wouldn't compile. getstring() was something i found in a really old book. I kinda figured it wouldn't work. what is the cin. ?
Feb 6, 2014 at 5:55am
I think getstring() might have been a Borland macro.
nolannpm wrote:
what is the cin. ?

What exactly are you asking? cin is an input stream wrapper, that has a few functions that I have used here to pause the console. The sync function 'synchronizes' the program's input stream with what is actually there, effectively ignoring everything in the console. Then, the get method is simply a function that 'gets' a single character, which can be used to pause the console until 'ENTER' (a single character) is pressed.
Feb 6, 2014 at 12:31pm
what is the cin. ?

It works same as your getstring() is supposed to do in your view.It accepts inputs values from keyboard .But it eats up all the blank spaces ie you cannot enter blank spaces for use like
Jack son(blank space b/w k and s)
so use cin.getline(size of string,name of character variable,delimiter);
Last edited on Feb 6, 2014 at 12:33pm
Topic archived. No new replies allowed.