Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hello
This is an example program that came with my book, it demonstates the use of the varable string, but i changed it a little so that the user could writte his own phrase
~The code~
#include<iostream>
#include<string>
using namespace std;int main(){
//define variables
string phrase;
string statement;
int pos;
//ask the user for a phrase
cout << "Enter a phrase: ";
cin >> phrase;
cout << "The phrase is " << phrase << endl;
//number of chars
cout << "The phrase's number of characters is " << phrase.size() << endl;
//ask the user for a position
cout << "Enter position:";
cin >> pos;
//Show the user what's the char in the chosen position
cout << "The charcter in position " << pos << " is " << phrase[pos] << endl;
//ask the user for an expression
cout << "Enter expression:";
cin >> statement;
//expression not found: inform the user of that
//expression found: say were the expression starts
if(phrase.find(statement) == string::npos){
cout << "No such statement found" << endl;
}else{
cout << "The statement " << statement << " begins at position " << phrase.find(statement) << endl;
}
system("Pause");
}The thing is, when I enter a phrase with multiple words an WINDOWS error msg shows up saying:
"stringObj.exe found a problem and will be closed, we are sorry for any...etc etc"Does the string object has some sort of limitation that stops the user from entering multiple words?? Or is there anything wrong with my compiler/my computer???
Best Regards
AMD ATHLON X2 5200 2.6ghz;
ASUS M2N-E SLI;
2GB DDR800 KINGSTON;
ASUS GF8600GTS;
Seagate 7200rpm 320GB;

The problem is that the string is space delimited. If you want multiple words, use cin.getline (). That will get the whole line up to but not possibly including the carriage return.

Thanks cup, but the getline() function only works with the variable char right? the only way was to use an array of chars but that way i woundn't be abble to use functions like erase(), size() etc right?
By the way can tell me whats the diference btw a variable and an object?
Best Regards
AMD ATHLON X2 5200 2.6ghz;
ASUS M2N-E SLI;
2GB DDR800 KINGSTON;
ASUS GF8600GTS;
Seagate 7200rpm 320GB;

You can use the function
std::getline(std::istream&, std::string&)
A good reference book for this sort of thing is "The C++ Standard Library" by Nico Josuttis.
(P.S. This answer is simplified, as actually there's no such function, but a template that can be used as though there was a function like the one above.)

The Josuttis book is a good one.
Deimos - in code, a couple of different flavors of 'getline':
cout << "Prompt 1:\n";
string s;
getline(cin,s);
cout << s << "\n";
cout << "Prompt 2:\n";
char buf[512];
cin.getline(buf,512);
string s2(buf);
cout << s2 << "\n";

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |