I try to get this to work...

for(int i = 0; i < size; i++){
		if(nameList[i] != NULL){
			//save name
		}
		else
			cout << "Namelist is full" << endl;
	}

but NULL is not exepted in a situation like this...or...?
I want to put in the name in the first free space in the array.
Help please.

Recommended Answers

All 8 Replies

We need to know about your "string array".

post declaration of nameList. If it's std::string namelist then there will never be a NULL entry.

its a namelist with the lenght of 100 and in the slots there is a name in its in the formate david:smith. So every slot in the array is not used and if every slot is used I want the program to say that every slot is used.
if there is no name in an entry isnt that entry null then?
It is in Java anyway...

if there is no name in an entry isnt that entry null then?

It depends, but the generally safe assumption is that the entry only contains what you explicitly store there. If you didn't initialize the entry to a null value, it's unwise to assume that an empty entry will be null.

It is in Java anyway...

C++ is not Java. Please post your array declaration so we can give you better advice on how to implement this search.

ok. here is what i came up with.

//introduced in main.
const int arraySize = 100,
string nameList[arraySize];

string* addName(string nameList[], int &listLenght){
	string fName, lName, name;
	int size = sizeof(nameList) / sizeof(nameList[0]); 
	system("cls");
	cout << "Skriv in förnamn: ";
	getline(cin, fName);
	cout << "\Skriv in efternamn: ";
	getline(cin, lName);
	name = fName + ":" + lName;
	for(int i = 0; i < size; i++){
		if(nameList[i].length() == 0){
			nameList[i] = name;
			listLenght++;
		}
	}
	return nameList;
}

instead of null I now try to investigate if the lenght of the content in namelist are 0.
Can this work?

Something like this:

name = fName + ":" + lName;
        
        // find the first free position
        int free_pos = -1 ;
	for(int i = 0; i < size; i++) 
            if( nameList[i].length() == 0 ) 
            {
                free_pos = i ;
                break ;
            }
        
        if( free_pos != -1 ) nameList[free_pos] = name ; 
        else cout << "Namnlistan är full\n" ;

Also how about clearing the content in the namelist array before using the add function

for(int i=0;i<size;i++)
{
   for(int j=0;j<namelist[i].length;j++)
              namelist[i][j] = '\0';
}

Maybe overkill but wont hurt

Thanks!
That will do it!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.