char array

How can I make this code work?
What I want to do is assign a string value to a char[] based on user input.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream.h>
int main()
{
char cat[20];
int n;
    cout << "enter a number 1 or 2\n";
    cin >> n;
    cin.ignore();
    if (n==1)
    {cat = "one not two";}
    id (n==2)
    {cat = "two not one";}
    cout << endl << cat;

}
1
2
3
4
#include <string.h>  // C library string functions
...
char s[ 20 ];
strcpy( s, "Hello, world!" );

BTW, if your compiler can handle it, it is better to use ISO/IEC C++ includes:
1
2
3
4
#include <cstring>
#include <iostream>
using namespace std;
...

Hope this helps.
This works for me (i compiled using Dev-c++)
#include <iostream>
using namespace std;
int main()
{
char cat [20];
int n;
cout << "enter a number 1 or 2\n";
cin >> n;
cin.ignore();
if (n==1)
{char cat [20] = "one not two";}
else if (n==2)
{char cat [20] = "two not one";}
cout << endl << cat;

}
It shouldn't. You've got three different variables named "cat" there.

1. There's the one declared on line 5 and used on line 14.
2. There's a local one declared on line 11.
3. There's another local one declared on line 13.

Line 14 should be printing garbage.
Duoas, I don't know enough of C++ to know how to use your suggestion but thank you.

Dynamic, Thank you for you post. I edited my program based on your example. Code::Blocks compiles the program but the output is garbage.

Did I do something wrong?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream.h>

int main()
{
char cat[30];
int n;
    cout << "enter a number \n";
    cin >> n;
    cin.ignore();

    if (n==1)
    {char cat[20] = "one not two";}

    if (n==2)
    {char cat[20] = "two not one";}

    cout << cat;
}

closed account (iw0XoG1T)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char cat[12];
int n;
    cout << "enter a number 1 or 2\n";
    cin >> n;
    cin.ignore();
    if (n==1)   strcpy(cat,"one not two\n");
    if (n==2)   strcpy(cat,"two not one\n");
    cout << endl << cat;

}
That worked perfectly. Thank you!
Now I can finish my program. =]
Topic archived. No new replies allowed.