I am StUCK:

I need help with the next code. I declared this array of "char". Then i send this array to a method called "operate_char"that expects a void pointer as argument. Dereference it the void pointer to get the value. But i only can print the first value and i want to print all the value. Can someone tell me what i am doing wrong????

Thnx

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
#include <iostream>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

void operate_char(void *msg, int size){

   char *p = (char*)msg ;
   
   for(int i=0; i<size; i++){
     
     cout << "Data contained within:" << *p << endl;
     *p++;

   }
}

int main(void){

        char line[3];
        cout <<"Voer 2 getallen in:" << endl;
        cin.getline(line,3);
        operate_char(&line, sizeof(line));

 return 0;
}

First off, let me say that I'm not really familiar with the cin.getline(line,3); that you're using. (I'm still a beginner myself.) That's where your problem is, though. This works just fine:


1
2
3
4
5
6
7
8
9
10
11
12
13
int main(void){

        char line[3];
        cout <<"Voer 2 getallen in:" << endl;
        for (int n=0;n<sizeof(line);n++)
        {
            cin>>line[n];
            }
        operate_char(&line, sizeof(line));
        system ("pause");

 return 0;
}


That's the easiest way I know of to iterate through a character array.

Here's how to do what you were trying to do:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

void operate_char( char *p )
{
    while (*p)
        cout << *p++ << endl;
}

int main(void)
{
    char line[3];
    cout <<"Voer 2 getallen in:" << endl;
    cin.getline(line,3);
    operate_char( line );
}

Dirk i wanted to work with void pointers but thnx for your input.

Gzero it works mate
Topic archived. No new replies allowed.