Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 653
Elliot Bonneville Avatar asked May 13 '10 01:05

Elliot Bonneville


People also ask

How do strings work in C?

A string in C is simply an array of characters. The following line declares an array that can hold a string of up to 99 characters. char str[100]; It holds characters as you would expect: str[0] is the first character of the string, str[1] is the second character, and so on.

What is string in C explain with example?

In C programming, a string is a sequence of characters terminated with a null character \0 . For example: char c[] = "c string"; When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character \0 at the end by default. Memory Diagram.

How do you declare a string in C?

Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax for declaring a string. char str_name[size]; In the above syntax str_name is any name given to the string variable and size is used to define the length of the string, i.e the number of characters strings will store.

What is string and how it works?

The technical description of a String is: an array of characters. The informal view of a string is a sentence. Strings are almost always written in code as a quoted sequence of characters, i.e., "this is a string".


3 Answers

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++.

like image 72
SoapBox Avatar answered Oct 21 '22 06:10

SoapBox


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.

like image 29
Owen S. Avatar answered Oct 21 '22 07:10

Owen S.


Use getline(cin, string); instead.

like image 2
Jon Purdy Avatar answered Oct 21 '22 06:10

Jon Purdy