Can they? When I have the user input a string that has spaces in it, my program goes crazy. Is this because strings can't have spaces, or is it something wrong with my program?
Can they? When I have the user input a string that has spaces in it, my program goes crazy. Is this because strings can't have spaces, or is it something wrong with my program?
A string can have spaces in it, but a lot of string-handling functions stop when they encounter a space.
The overloaded >> operator is designed to stop at whitespace. You might look up:
istream::getline()
string::getline()
Both will read in tabs spaces and stop a newline (or other delineator if supplied).
Can anything be done about that? All I'm doing with the string is putting it into a vector and displaying on the screen.
Be done about what?Code:#include <iostream> #include <string> #include <vector> using namespace std; int main(int argc, char *argv[]) { vector<string> stuffs; string vectorBuf; // Reads input into "buffer" and pushes it onto vector for(int i = 0; getline(cin, vectorBuf, '\n'); ) { stuffs.push_back(vectorBuf); } // Iterates through the vector spitting out it's contents for(vector<string>::iterator iter = stuffs.begin(); iter < stuffs.end(); iter++) { cout << *iter << endl; } }
Yes - he just showed you. When you use the << operator, you're actually calling a function (even though you don't really see this) that stops when it encounters a space. If you use the getline functions like he showed you, they will accept spaces, and only stop once they get to a newline character. You can look through www.cppreference.com to find other functions and their behavior.Can anything be done about that?
getline(cin , instring , '\n');
where cin is where4 your getting your input from
where instring is your string variable
and '\n' is your delimiter.
for use of this you must include <string>
header, if you are currently unaware
you can define instring like this
string instring;