Change letter to word?

Making a basic code that just asks you to type in a letter. Then says You Typed In (Letter) !. Curious to know if there is a way to make it accept a word? This is the code.

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

int main(void)
{
    char cha;

   cout <<"Please enter a letter" <<endl;
   cin >> cha;
   cout << "You typed in " << cha << "!" << endl;


return 0;
}
A char variable only holds one character. Multiple characters can be handled with character arrays or strings.

There's introductory info on these in the tutorial on this site here:
http://www.cplusplus.com/doc/tutorial/ntcs/
Thanks so much for that. This is my code now:

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

int main(void)
{
    char foo [25];

   cout <<"What is your name?" <<endl;
   cin >> foo;
   cout << "Nice to meet you " << foo << "!" <<endl;
return 0;
}


So when I type in my name it only record my first name because I hit space. Any way to do something about that or?
Last edited on
Yes. First, use strings, it is much easier (and there is no limit that you have to set on its length - it can grow as you need). Then there is a function called getline, which does what you want. Here is an example:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string> // strings

int main() {
    std::string foo; // declare a string

    std::cout << "What is your name? " << std::endl;
    std::getline(std::cin, foo); // retrieve a line of input from cin, and put it in foo
    std::cout << "Nice to meet you, " << foo << "!" << std::endl;

    return 0;
}
Topic archived. No new replies allowed.