expected unqualified-id before '{' token

Hi im trying to write a little program to fool my friends. Im trying to compile it with g++ or what ever the terminal uses but it gives me the "expected unqualified-id before '{' token" error.

Heres the code:
1
2
3
4
5
6
7
8
9
10
11
#include<iostream>
using namespace std;

int main();
{
	int name, answer;
	cout << "Please enter your name: ";
	cin >> name;
	cout << "Hello " << name << ", would you like a doughnut?(y/n)";
	cin >> answer;
	if (answer = y){
There's quite a few things that are wrong here. First thing to note is that this code is not your entire code, and if it is, you are horribly wrong. Now, on to the problem solving. You are, firstly, trying to make a name and answer integers, whereas they should respectively be char* (or std::string) and char. Afterwards, you do not consider y a character, but a variable (which you did not declare). Considering the case that this code is not complete, you forgot to add two }'s and your code does absolutely nothing. You also add a semicolon at the end of int main(), do NOT do this. Ever. Lastly, you put (answer = y), this will cause answer to be changed to y's value, in which y (as earlier stated) is not a variable. You would be better off using (answer == 'y'), as this compares answer to the character y.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string> // Add this to support strings
using namespace std;

int main()
{
	string name;
        char answer;
	cout << "Please enter your name: ";
	cin >> name;
	cout << "Hello " << name << ", would you like a doughnut?(y/n)";
	cin >> answer;
	if (answer == 'y')
        {
                // Input your code here
        }
}
Last edited on
Thanks for the help. I knew I had alot of problems but boy. The rest of the code isnt really worth showing any way. Thanks.
Just one note, I forgot to state that you should use getline() whenever you input strings. Just replace cin >> name; with: getline(cin, name);

G'luck with your program ;)
Topic archived. No new replies allowed.