my first code.

Hi im very new and i need help with my first code.even though i clearly stated cat=0 it still does string word.......
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using namespace std;

int main()
{
  int cat=0;
  if (cat=1)
  {
  string word;
  cout<<"Please enter a word: ";
  cin>> word;
  cin.ignore();
  cout<<"You entered the word: "<< word <<"\n";
  cin.get();
  }
  else
  {
  int num;
  cout<<"Please enter a number: ";
  cin>> num;
  cin.ignore();
  cout<<"You entered the number "<< num <<"\n";
  cin.get();
  }
}
Last edited on
I'm going to repost your code within code tags so that I can comment line-by-line:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>

using namespace std;
int main()
{
	int cat;
	cout<<"word or number?";
	if cin>>"word";
	{
		(cat=1)
	}
	if cin>>"number";
	{
		(cat=2)
	}
	else
	{
		cout>>"write word or number";
	}

	if (cat=1)
	{
		string word1;
		cout<<"Please enter a word: ";
		cin>> word1;
		cin.ignore();
		cout<<"You entered the word: "<< word1 <<"\n";
		cin.get();
	}
	else
	{
		int num;
		cout<<"Please enter a number: ";
		cin>> num;
		cin.ignore();
		cout<<"You entered the number "<< num <<"\n";
		cin.get();
	}
}
Lines 8 and 12: You can't read from the input stream 'cin' into a constant character array. You could read into a string variable instead:

You need a loop (like a do-while loop) so that the first input process can repeat if the user doesn't enter 'word' or 'number'.

Lines 8 and 12: 'if' control structures need a condition that can evaluate as true/false inside round brackets (...). No semicolon at the end of this line...

Lines 10 and 14: Don't forget the semicolon at the end of the line.

Line 18: Should be cout << ...

Line 21: You have an assignment operator, you should be using the comparison operator ==.

Line 1: Don't forget to #include <string>

That's a lot to take in. Here's a fixed version, but I suggest you don't look at it until you have a go yourself...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <string>

using namespace std;
int main()
{
	int cat = 0;
	string myString;
	do
	{
		cout<<"word or number?";
		cin>>myString;
		if(myString == "word")
		{
			cat=1;
		}
		else if(myString == "number")
		{
			cat=2;
		}
	}while(cat == 0);

	if (cat==1)
	{
		string word1;
		cout<<"Please enter a word: ";
		cin>> word1;
		cin.ignore();
		cout<<"You entered the word: "<< word1 <<"\n";
		cin.get();
	}
	else
	{
		int num;
		cout<<"Please enter a number: ";
		cin>> num;
		cin.ignore();
		cout<<"You entered the number "<< num <<"\n";
		cin.get();
	}
}

Thank you so much for taking your time to help me. taught me alot.TY:)
Last edited on
Topic archived. No new replies allowed.