Archived

This topic is now archived and is closed to further replies.

Darkan_Fireblade

Help! I can't figure it out!

Recommended Posts

why do i get and illigal opertion when i try to typ in some thing i my program? here is the code #include <iostream> using namespace std; int main() { cout << "Hi whats your name\n"; cin >> "Computer 1\n"; cout << "Hello world\n"; return 0; } please help! Sir Darkan Fireblade

Share this post


Link to post
Share on other sites
cin and cout are called 'streams', they're objects that (usually) represent the flow of characters from and to the console window. The output stream is what your program outputs, the input stream is what the user of your program types in response.

When you say:


cout << a_variable;


that means "insert the value of 'a_variable' in the ouput stream". Similarly, you can read:


cin >> a_variable;


as "extract a value from the input stream and put it in 'a_variable'".


Notice that what I'm doing here is different from what you are doing: you're using a quoted string, or a string literal. A literal is a hard-coded value, it's not a variable so you can't assign a value to it.

That should clear up why this works:


cout << "Hi whats your name\n";


and why this doesn't:


cin >> "Computer 1\n";


You can insert the value "Hi whats your name\n" in the output stream, but you can't extract a value from the input stream and put it in another hard-coded value. To make it work, you have to change your program so it looks something like this:

      
#include <iostream>
#include <string> //for 'string'


using namespace std;

int main()
{
string name; //create a variable


cout << "Hi whats your name: "; //ask user to type his name

cin >> name; //read a value and save it in the variable

cout << "\nHello " << name << "!\n"; //you can write several things at once

return 0;
}


hope that makes any sense to you...

Edited by - kvh on February 7, 2002 3:15:05 PM

Edited by - kvh on February 7, 2002 3:15:41 PM

Share this post


Link to post
Share on other sites