Elliot Bonneville
Elliot Bonneville

Reputation: 53351

Working with strings in C++

I'm working with strings in C++. I recently came across a problem when entering strings. I'm using cin >> string; to get my string as user input. When the user enters a space into the string, the next input is automatically filled out with the remaining letters, or sometimes left blank. As the next input string is often an integer, this will result in an unpleasant bug. What's a good fix for this?

EDIT: Here's the current code:

cout << "Please print the enemy's name: ";
getline(cin, enemyName);

Upvotes: 5

Views: 767

Answers (4)

SoapBox
SoapBox

Reputation: 20609

You probably want to get all input into the string up until the user presses enter. In that case, it can be said that what you really want is to read a "line" of text. To do that, you'd use std::getline, like so:

std::getline(cin, enemyName);

That is assuming enemyName is defined as an std::string. If enemy name is a c-style charater array, you'd want to use cin.getline, like this:

cin.getline(enemyName, sizeof(enemyName));

But, try to avoid using C-style character arrays at all in C++.

Upvotes: 7

Owen S.
Owen S.

Reputation: 7855

The behavior of >> with strings is intentional; it interprets whitespace characters as delimiters to stop at, so it's really best at chomping words. std::getline() (#include <string>) uses '\n' as the delimiter by default, but there's also a version of std::getline() that takes a custom delimiter character if you need it.

Upvotes: 3

dave4420
dave4420

Reputation: 47062

Use getline() to read in an entire line at a time.

getline (cin, string);

Upvotes: 2

Jon Purdy
Jon Purdy

Reputation: 55069

Use getline(cin, string); instead.

Upvotes: 2

Related Questions