Hi guys,

I am new to C++ and am trying to display the contents of an array in the form of {1,2,3,4} but am having some difficulties, they get printed but there is a trailing comma {1,2,3,4,}....how can I get rid of this?

this is my code:

cout << "\nArray: {";
	for(int i = 0; i < currSize; i++){
		cout << darr[i] << ",";
	}
	cout << "}";

thanks

Recommended Answers

All 3 Replies

Cause your program asks for the trailing ",".

Put a condition in where it will only output if it is not the last element or break outta the loop if it is on the last element instead of displaying a comma.

#include <iostream>
using namespace std;

int main()
{
	int myArray[] = {1,2,3,4,5,6,7};
	int szArray = sizeof(myArray)/sizeof(int);
	cout << "\nArray: {";
	for( int i = 0; i < szArray; i++ )
	{
		cout << myArray[i];
		if( i != szArray-1 )
			cout << ", ";
	}
	cout << "}";
	system("PAUSE");
	return 0;
}

Put a condition in where it will only output if it is not the last element or break outta the loop if it is on the last element instead of displaying a comma.

I prefer to print the first element outside the loop, then you only need to check the size of the array once, rather than every time the loop iterates. This might speed things up if you have a very large array (although printing to the console is probably the rate-limiting step, not checking whether to print a comma or not). Anyway, my personal preference would be to go with something like:

int myArray[] = {1,2,3,4,5,6,7};
unsigned szArray = 7;
std::cout << "\nArray: {";

if(szArray > 0)    std::cout << myArray[0];

for(unsigned i = 1; i < szArray; ++i)
    std::cout << ', ' << myArray[i];

std::cout << "}";
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.