C++ Beginner: std::cin to std::string - c++

Just started learning C++ and encountered an issue with strings while doing an exercise.
So I initialized std::string phrase; while allowing the user to input and save the phrase to the string with std::cin >> phrase;. Now my issue comes when the inputed phrase has spaces, I noticed that the computer will only save the characters up till the first word only.
With the phrase "sunsets are great", the phrase.size() only came out to 7, so the following words after the first space were not saved.
The entire exercise is supposed to compare all of the letters in the whole inputted string with another set of values. Should I be using a different function for this?
Any help would be appreciated! :)

I have also had this problem when i was first starting out.
whenever you want to read a string i would use the getline.
ie
string phase
cout << "enter phase" <<endl;
getline(cin,phase);

If you want to take an entire line including space(s), you may use the following code:
string str; // declaration
getline(cin, str);
Remember: cin.get and cin will trim all the inputted characters just after first space.
Enjoy.

Related

difference between input using ignore and so on

I wanted to clear some doubt regarding the function
cin.ignore(1,'\n');
code:
char x[80];
cin>>x;
cin.ignore(1,'\n');
If user input the word: paul Smith
does the program looks for the first space in the word and ignores/delete the rest of the characters?
Hence the program takes paul only and discards Smith?
Am I right?
I'm getting confused! Please explain in really simple words because I cannot understand the explanation on google regarding this issue.
cin.ignore(1,'\n');
is not very useful. It will ignore only one character.
cin.ignore(100,'\n');
will ignore up to 100 characters but will stop after it encounters a '\n'.
In your case,
cin>>x;
will read paul into x. The line
cin.ignore(1,'\n');
will consume the space after paul. Hence, Smith will be left on the input stream.
Hence the program takes paul only and discards Smith?
No. I hope that is clear from the above.
cin >> x;
Since x is a string or char array, this reads one word (everything up to the first whitespace character) from the input, and stores it in x.
cin.ignore(1, '\n');
reads and ignores one character from the input. It won't read the whole rest of the line. More generally:
cin.ignore(n, delim);
reads and ignores characters until it has either read n characters or reached a character equal to delim. If you want to ignore until the end of the line, no matter how many characters that is, do:
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Reading whole line with std::cin

I would like to figure out how to read a whole line (including spaces) with std::cin. I am aware of the existence of std::getline, I would just like to figure out how to do it with std::cin so I can better understand iostream in C++. I've tried using a for loop with std::cin, however it keeps reading past the end of the line. Any help would be greatly appreciated.
Also the cin << only allows us to enter one word into a string.
However, there is a cin function that reads text containing blanks.
std::cin.get(name, MAX);
get will read all characters including spaces until Max characters have been read or the end of line character (ā€˜\nā€™) is reached and will put them into the name variable.
You should decide what is MAX.

Splitting user input by one space for the first two words, then storing the remaining phrase (C++)

Right now I'm trying to, and as the title says, find a way to split a string in a weird way.
Lets say the input looks like:
1234.5/N 1222.2/W Taco Tuesday
And the input given for the first two words separated by spaces will always be in the format #.#/(N/S/W/E)
The problem I'm having is with the last word. This word can be as many spaces as it wants to be and is only "terminated" by a newline.
My first try was doing:
std::string input1; // number/Letter
std::string input2; // number/Letter
std::string input3; // word
std::cin >> input1 >> input2 >> input3;
The problem is, obviously is that if input 3 has a space in it, cin won't capture anything past that last space.
I thought about using getline(cin, input), but I realized I would get a single string with everything in it, instead of 3 separate strings. I believe this would be more challenging to extract the numbers out of the first two (probably by using find(/)), somehow keeping the letter after the slash, then moving to the next number, extracting that, keeping the letter after, and finally getting the rest of the phrase, minus the letter after the slash.
Also I would have to store the numbers in separate variable for calculations, take note of the letter used, and keep the last phrase.
Is there any reasonably elegant way to do this using std::string or at the very least is there just some way to at least extract the first two words and then store the remaining phrase into a string?
You can try to read first two words with cin and then use getline:
cin >> input1 >> input2;
getline(cin, input3);

Parsing Matching Multiple Possible Strings in a Text Adventure.

I'm in my first semester of university and I have to make a text adventure game in c++.
So far we've done arrays, structs, and pointers. I've tried to google my problem, however most other users use classes which we have not yet done.
The professor would like us to use commands like Go North, open door with key etc.
I've managed to make it work by using hotkeys like n to go north, but obviously I would like to do it like he wants us to.
So my question is; how can I make a command consisting of several strings?
The problem is that we need to create libraries for the command, the object and (if there is the possibility in this room to combine two things) the preposition with another object. In each library there should be the words to use, for example: Commands are: Use, go, talk, read, etc...
Taken from http://www.cplusplus.com/reference/iostream/istream/getline/
#include <iostream>
using namespace std;
int main () {
char name[256], title[256];
cout << "Enter your name: ";
cin.getline (name,256);
cout << "Enter your favourite movie: ";
cin.getline (title,256);
cout << name << "'s favourite movie is " << title;
return 0;
}
Try search for the getline or scanf function. Both reads a formatted string from the stdin(in your case the prompt command). You could use cin directly too, the problem is that cin return a string composed of the characters until the first whitespace.
If you're asking how to read the multi-word commands, then you can use getline() to read a line of input as a string, and then a stringstream to read each word from that line, something like this:
std::string line;
while (std::getline(std::cin, line)) {
std::istringstream stream(line);
std::string word;
while (stream >> word) {
// do something with this word
}
}
Use something like std::string input << std::cin; to input a line of text.
Split your string by whitespace/the space character.
Next steps:
Do command tokenization into verb/noun pairs, like Open/Door and Go/North
Make classes that represent your verbs, and design them to operate on objects or specific nouns
Some subjects to look up:
Text adventure command parsing on google
Interactive fiction on wikpedia
I guess you are using cin to read the commands? In that case get input into a string, use find to find the spaces in it, and substr to extract the command and its arguments. Try to convert all substrings to either lower- or upper-case, as it will be easier to compare them later.
Now take the command substring and compare it to all commands you have. When you find a match, call a special function that executes the command, passing the arguments to the function. E.g., for the "go" command you could have a go function, which takes the direction as argument.

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);
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++.
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.
Use getline(cin, string); instead.
Use getline() to read in an entire line at a time.
getline (cin, string);