?
Solved

How to use a string with a space?

Posted on 2003-03-18
21
Medium Priority
?
227 Views
Last Modified: 2010-04-01
I need to know how to use a string with a space.

I did

string s;
cin>>s;

when i typed in "Hello World"
and i do:

cout<<s;

it only shows "Hello", but the World disappeared.  How do i make it so that both words or more will be include in s?

so in the future i could use

if (s == "hello world")




Also how should i create a simple code so that when i asked the user to input a string, and any word in that string will be in the "if" statement.

for example, i asked the user to cin>>s;

if the user inputs "go to bathroom"

I want an If statement so that if any word in the string "s" contains the word "bathroom", the if statement will execute.


e.g. the user inputs "go to bathroom" or "bathroom" or "go in bathroom" , the if statement will executes.

What should the if statement look like?
0
Comment
Question by:SuperSid
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 11
  • 6
  • 4
21 Comments
 
LVL 2

Expert Comment

by:DarthNemesis
ID: 8161603
cin only takes one word at a time. You can use getline(cin, s); to input a whole line.

As for finding a certain string, if you want it to accept exact words only, one of the easiest ways is to use a stringstream.

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

void main() {
        string x;
        getline(cin, x);
        stringstream s;
        s << x;
        string find;
        while (!s.eof()) {
                 s >> find;
                 if (find == "bathroom") {
                        // add your code here
                 }
        }
}
0
 

Author Comment

by:SuperSid
ID: 8161645
Hehe i'm really new to c++ and don't know a lot of codes.

I sorta know what getline is, but not stringstream. Could you add comments on what they do?  like that s<<x and the (!s.eof())

thx
0
 

Author Comment

by:SuperSid
ID: 8161662
Hehe i'm really new to c++ and don't know a lot of codes.

I sorta know what getline is, but not stringstream. Could you add comments on what they do?  like that s<<x and the (!s.eof())

thx
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 4

Expert Comment

by:n_fortynine
ID: 8161739
i think cin's getline takes a parameter char*, not string so basicly he can just do
char* str = new char[80];
cin.getline(str);
then to compare this just use strcmp(char*, char*)
in this case strcmp(str, "hello world");
strcmp returns 0 if they're equal, -1 if the 2nd > 1st and 1 if 1st > 2nd
0
 

Author Comment

by:SuperSid
ID: 8161913
Hehe i'm really new to c++ and don't know a lot of codes.

I sorta know what getline is, but not stringstream. Could you add comments on what they do?  like that s<<x and the (!s.eof())

thx
0
 
LVL 2

Accepted Solution

by:
DarthNemesis earned 80 total points
ID: 8161945
That's right n_fortynine, passing a string as getline's parameter casts the char* to the string. However, SuperSid wants to compare each individual string in the input, and not the entire string. I picked stringstream because it's less complicated than a tokenizer.

Anyway, SuperSid:
 << is the insertion operator and >> is the extraction operator. When you have any kind of a stream, using these operators will either add or remove data to/from the stream's buffer (data stored in memory).
s << x adds the string 'x' to the buffer stored by stringstream 's', and ss >> find extracts one string out of that buffer and stores it in string 'find'.

eof() stands for end of file, and it's used by all stream classes derived from ios (input/output stream). The stream has a 'get pointer' and a 'put pointer' that keep track of where in the buffer the stream is reading from or writing to, respectively. When you extract data from the stream using >>, the get pointer will change to the position of the next string in the buffer. When you've extracted the last string from the buffer, the get pointer will be at the end of the buffer. That's where eof() comes in - it returns true if there's nothing left in the stream to extract.

Hope I didn't make that too complicated! =) Just ask if you need more clarification on this.
0
 
LVL 2

Expert Comment

by:DarthNemesis
ID: 8161992
I don't know how much you've learned about classes, so I'll clarify one more thing:
Classes are a collection of variables and functions designed to make coding simpler or more organized. The stringstream class is made up of several 'members' - a buffer and the two pointers - and has a bunch of functions that let you interact with them. The . operator accesses a member or member function of a class, so s.eof() means run the function eof() that's a member of stringstream s. The ! operator just reverses a boolean condition, i.e. !true is the same as false. So the condition (!s.eof()) means that s is not at the end of its buffer, and that there are more strings to read from it.
0
 
LVL 4

Expert Comment

by:n_fortynine
ID: 8162039
DarthNemesis, sorry I didn't read the last part of his question =) I think you've got the answer to his question.
0
 

Author Comment

by:SuperSid
ID: 8162215
sorry about that repeated post from hitting the Refresh button.

hahah it's a lil complicated, but i'm trying my best to understand.

could you write a sample code to simply ask the user to input any words, and if one of the words contain the word "bathroom", it will execute a function?  or just an exact word say "go in bathroom".  I tried doing

string ans;
cin.getline(ans);

but some kinda error occurred.

also
getline (cin, ans);  

when i execute this, it lets me enter the string Twice.  and it seems like for every word my If statement occurs or something and i'm confused hahah.  So could u write the simplest function to ask the user to input any number of words, or exact words if that's easier, and write an if function so that the 'ans' contains the word "bathroom" or just exact words "go in bathroom"?
0
 

Author Comment

by:SuperSid
ID: 8162256
if my question is confusing, this is how the code i think should look like.

cout<<"You are in your room.  There is a door to the bathroom, and a door to the living room.\n";
cin>>ans; //this is the part i don't get.  How do i get the user to input any numbers of words?

if (ans == "bathroom") //this If statement checks for if the 'ans' contains the word "bathroom" but i don't know how to write it.

cout<<"you have entered your bathroom\n";

0
 

Author Comment

by:SuperSid
ID: 8162265
once executed i want it to look like:

You are in your room. There is a door to the bathroom, and a door to the living room.
(enter something)
e.g. Go into the bathroom (or go in bathroom or get in bathroom)

You have entered your bathroom.
0
 

Author Comment

by:SuperSid
ID: 8162326
AHhhh i think i got the

while (!s.eof())

statement that you wrote.

But still the

s<<x

and

s>> find

are still a little confusing.  Could someone explain this?  i know very little about c++.
0
 
LVL 4

Expert Comment

by:n_fortynine
ID: 8162421
like DarthNemesis said, s << x will put the content of the string x into the buffer that stringstream creates like so
before: _ _ _ _ _ _ _ _ _ _ _ ...
after:  h e l l o _ w o r l d
then using the extractor >> we get part of the buffer to the variable, i.e. doing s >> find will make this to happen:
before: find is "empty" and hello world is in buffer.
after: find contains "hello" and the pointer in the buffer stops in front of "world."
does that make any sense?
0
 

Author Comment

by:SuperSid
ID: 8162490
Yup i got it.  Now the getline (cin, s) makes me input 2 lines.  THis is the code:
       cout<<"Enter something\n";
       string ans;
       getline(cin, ans);
       stringstream s;
       s << ans;
       string find;
       while (!s.eof())
          {
                s >> find;
                if (find == "bathroom")
               {
                          //code
                        }
                }

     


when executed, it goes like this:

Enter something.
(i entered "go in bathroom" and hit ENTER)

then it waits for me to enter something again.
(then i entered anything)

why does it do this?  Shouldn't it ask me only once?
0
 
LVL 2

Expert Comment

by:DarthNemesis
ID: 8162740
I've had that happen before, but only if I used cin previously. Do you have any code before what you posted?

When you use cin << s, if the user types more than one word, the cin buffer will still have some data left over. If you try to use getline after that, the program can mess up - it might ask you twice, or skip over it completely. To avoid this, you have to empty out the cin buffer. The easiest way to do this is using ignore() - after your cin, put cin.ignore(100); (some large number).
0
 

Author Comment

by:SuperSid
ID: 8162973
how do you use a cin.ignore(100)?  

i did

cin>>s;
cin.ignore(100)

and when executed, it wouldn't stop letting me cin.
0
 
LVL 2

Expert Comment

by:DarthNemesis
ID: 8162998
Hmm... try cin.ignore(100,'\n');
0
 
LVL 4

Expert Comment

by:n_fortynine
ID: 8163090
i assume s is a string?
this is, like DarthNemesis said, because there are "stuff" from previous entries remaining in the buffer, which is most likely the "enter" part that was not taken cared of.
How about trying:
cin >> s;
cin.get();
0
 

Author Comment

by:SuperSid
ID: 8163109
that's it!  that's the command!  thanks!
cin.ignore(100,'\n');
0
 

Author Comment

by:SuperSid
ID: 8163275
that's it!  that's the command!  thanks!
cin.ignore(100,'\n');
0
 
LVL 2

Expert Comment

by:DarthNemesis
ID: 8163460
Maybe you should lay off the refreshing for a while... =P
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
Suggested Courses

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question