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;
}
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.
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;
}
#include<iostream>
#include<cstring>
usingnamespace 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;
}