retrieving characters of string individually

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <string>
#include <iostream.h>

main()
{
      char a[3] = "ab";
      char b1[2];
      char b2[2];
      b1 = a[0];
      b2 = a[1];
      cout << a << '\n';       // outputs ab
      cout << b1 << '\n';      // outputs a
      cout << b2 << '\n';      // outputs b
      cin.get();
      cin.get();
      
      return 0;
      }


for some reson i get these errors for lines 9 and 10:
incompatible types in assignment of `char' to `char[2]'
What am I missing here? I'm using Dev C++ compiler version 4.9.9.2.
It's because you are trying to assign an array to a character. It's very clear - take a look at it. How can you assign an array of characters to one individual character? If you intend to assign an array to an element of another array it must be MD. (multidimensional)
EDIT: Check the articles for Disch's article on the dangers of MD arrays. It's very clear and it has some things you should be sure to keep in mind before getting bogged down in MD arrays.
Last edited on
you dont need to declare array's for b1 & b2, they will take on the value of the character in the string that is assigned to them

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

#include <string>
#include <iostream>
using namespace std;


int main()
{
    char b1;
    char b2;
    char a[3] = {"ab"};

    b1=a[0];
    b2=a[1];
      
    cout << a << '\n';       // outputs ab
    cout << b1 << '\n';      // outputs a
    cout << b2 << '\n';      // outputs b

    cin.get();
    cin.get();
      
    return 0;
}


I see you have some more inputs after this arguement is complete, what are those intended for?
Last edited on
Probably to prevent the console from snapping shut.
You can do the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <string>
#include <iostream.h>

main()
{
      char a[3] = "ab";
      char b1[2] = "";          //you should initialize it.
      char b2[2] = "";          //you should initialize it.
      b1[0] = a[0];
      b2[0] = a[1];		
      cout << a << '\n';       // outputs ab
      cout << b1 << '\n';      // outputs a
      cout << b2 << '\n';      // outputs b
 //     cin.get();      I think one is enough.
      cin.get();
      
      return 0;
}


ab
a
b


Last edited on
also may want to change it to be more like C++ standard code:
as bettyboops example. you too bolo809 :)
Last edited on
Isn't it actually the opposite of what tummychow said? b1 and b2 are arrays, so saying
1
2
(char[2])b1=(char)a[0];
(char[2]b2=(char)a[1];

gives an error, no?

Shouldn't it be
1
2
b1[0]=a[0];
b2[0]=a[1];


Though, if that's then followed by cout's, you'd also have to place some '\0''s to prevent it from stampeding through your memory.

Or BettyBoopTS' far simpler version. Because, you know, it's simpler.
okay thanks everybody. It was kind of a "duh" thing once I saw what I needed to do. :)
Topic archived. No new replies allowed.