Hi there, I've been writing in c++ for a little while now and am starting to feel more confident, I've noticed a possible error in a game I've been making, it is that when the player is inputting a character name, it is a possibility that they may put in spaces, now if you use string or char type variables they will not allow you to do this.

Is there a way to use a variable that can handle spaces as well as text? Or even a universal variable (you never know : ) )

any help appreciated
Dan

Recommended Answers

All 2 Replies

strings can hold space char and other whitespace char as well, once you know the details of how stream methods and overloaded operators work. Short story, use getline(), there are two versions, one for C style strings and one for stl string objects.

To expand on Lerner's answer, you're probably reading strings like this:

#include <iostream>
#include <string>

int main()
{
  std::string name;

  std::cout << "Name your character: ";
  
  if (std::cin >> name)
    std::cout << "Hello, " << name << '\n';
}

When cin works with the >> operator, it reads words. A word is defined as ignoring leading whitespace, then any number of non-whitespace characters. If the character name has embedded whitespace, only the first word will be stored in the string variable, and the other words will still be in the stream, ready to mess things up later on. ;)

The getline function is different in that you can specify a single character that says when to stop reading, and the default is a newline character:

#include <iostream>
#include <string>

int main()
{
  std::string name;

  std::cout << "Name your character: ";
  
  if (std::getline(std::cin, name))
    std::cout << "Hello, " << name << '\n';
}

There's an optional third argument that acts as the delimiter. Say instead of a newline you wanted to use a pipe, you might change the call to this:

std::getline(std::cin, name, '|')
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.