Programming on Mac

Hi All,

I am new to C++ and also on Mac. I installed Xcode to start writing C++ code on mac as I am learning. I created a command line utility project using C++. I was able to run the standard helloworld program, but when I ran the following code. I got the error: expected unqualified-id before 'public'. Can some one tell me what am I missing here? Do I need a header file to specify the function I am using?

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

public static boolean isUniqueChars2(String str) 
{ 
	boolean[] char_set = new boolean[256]; 
	for (int i = 0; i < str.length(); i++) 
	{
		int val = str.charAt(i); 
		if (char_set[val]) return false; 
		char_set[val] = true;
	}
	return true;
}

int main (int argc, char * const argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
	isUniqueChars2("Nikhil");
    return 0;
}


The error is:
1
2
3
error: expected unqualified-id before 'public'
error: expected unqualified-id before 'public'
error: expected unqualified-id before 'public'
Is it just me or did you post some java code?
Here's a translation:
1
2
3
4
5
6
7
8
9
10
11
12
13
bool isUniqueChars2(std::string str){//don't forget to include <string>
//though char* would work here too
    bool char_set* = new bool[256];//Though bool char_set[256] would be better
    //you will then have to initialize the array to 0.
    //see memset or std::fill
    //another option is bool char_set[256] = {0};
    for (int i = 0; i < str.length(); i++){
        int val = str[i];//this may cause problems if your string contains non ASCII chars.
        if(char_set[val]) return false;
        char_set[val] = true;
    }
    return true;
}
Global functions can't be public. This is the only valid use of the public keyword in C++:
1
2
3
4
5
class A{ //OR struct A{
//...
public:
//...
};

'boolean' is not a type in C++. 'bool' is.
Dynamically allocated arrays are assigned to pointers, not to "arrays" as in Java:
bool *char_set = new boolean[256];
Memory is managed manually in C++. Your function isn't freeing the memory allocated for the array char_set points to:
1
2
//(Before every exit point after char_set has been initialized.)
delete[] char_set;

'String' isn't a standard type. 'std::string' is. std::string, however, doesn't have a member charAt(). Instead, it has std::string::at() and std::string::operator[]().
thanks a lot hamsterman....your translated version worked fine...it was a java code which i misunderstood as cpp since i dont know java. but thanks a lot...i will pay attention to the syntax !
Thanks helios, i was just reading about dynamically allocated arrays as you just pointed.
Topic archived. No new replies allowed.