Help with char*!

Hi! I'm having some trouble with char pointers, arrays and all that stuff.
I wrote a simple programme which should let me know every time it finds a letter 'a' in an array. But it outputs nothing even if I write only 'a's.
Here's my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
char * input;
void Check();
void Get();
int main(){
Get();
Check();
}

void Get(){
string aux;
cin>>aux;
input=(char*)aux.c_str();
cout<<input;}

void Check(){
	for(int i=0;i<(int)strlen(input);i++){
		if(input[i]=='a')cout<<"There's an 'a' within the array"<<endl;}
}

What's going on? Help me please!
Thanks!
Last edited on
This:
dfsa
dfsaThere's an 'a' within the array

is a run of the code below.

Maybe your code doesn't compile? Or you're not running it once it has compiled?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <cstring>

using namespace std;


char * input;
void Check();
void Get();
int main(){
Get();
Check();
}

void Get(){
string aux;
cin>>aux;
input=(char*)aux.c_str();
cout<<input;}

void Check(){
	for(int i=0;i<(int)strlen(input);i++){
		if(input[i]=='a')cout<<"There's an 'a' within the array"<<endl;}
}

1
2
3
4
char * input;
...
input=(char*)aux.c_str(); // You don't have to cast it,
        // since c_str() already makes it a c-style string. 
Last edited on
#Moschops, I compiled it several times, even added a cout<<whatever, changed the variable names, rebooted my PC, but still doesn't work!
How is this possible?
Here's the complete code with some cout<<...'s I put to see if anything changed. I am using Visual Studio C++ 2010 Express.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
#include<string>
using namespace std;
char * input;
void Check();
void Get();
int main(){
Get();
cout<<"BLABLABLA"<<endl;
Check();
}

void Get(){
string aux;
cin>>aux;
input=(char*)aux.c_str();
cout<<input;}

void Check(){
	cout<<"OK"<<endl; /*It prints until this line, and then nothing*/
	for(int i=0;i<(int)strlen(input);i++){
		if(input[i]=='a')cout<<"Letter 'a' found"<<endl;
	}
}


What is wrong here? There isn't any error while compiling or running, and yet what I need doesn't happen.
Last edited on
The string aux is local to your Get() function.

As soon as you exit the Get function, aux is no longer in scope. i.e. its storage is no longer allocated and the char * input pointer is no longer valid.
Thanks, AbstractionAnon! I just replaced the Get function with this:
1
2
3
4
5
6
7
8
9
void Get(){
string aux;
cin>>aux;
input=new char[aux.size()];
int i:
for( i=0;i<aux.size();i++){
	input[i]=aux[i];}
input[i]='\0';
}
Topic archived. No new replies allowed.