Friday, July 31, 2009

A problem with a array of a string type?

I declared a string as array like this string GInfo[500] in my item.h; and i have function were you enter the item. I call this function from my seller.cpp, I also pass a integer that acts as the counter. So it looks something like this


seller.cpp





int num2=0;


while ( obj2 != "n")


{


cout %26lt;%26lt; "Would you like to enter a item to sell? "; cin %26gt;%26gt; obj2;


if (obj2=="n")


{ break;


}


SItem.Info(num2); // Calls the function in item.h and sends integer num2 to act as a counter


num2 = num2 + 1;


}





**some of my item.h**





item.h


void Info(int num)


{


cout %26lt;%26lt; "What are you selling? ";


cin %26gt;%26gt; GInfo[num];





*testing to check if my array was holding the string.





for (int i=0;i%26lt;=num;i++)


{


cout %26lt;%26lt; GInfo[num] %26lt;%26lt; endl;


}


}


When I run my program if I enter one item it will print but if I enter more than one item it displays the last item multiple time. (ex. If I enter a widget as my third item it will print widget three times replacing anything previous. (widget widget widget)

A problem with a array of a string type?
Check your for loop right there, you need to use the variable i instead of "num" as your indexer.





cout %26lt;%26lt; GInfo[i] %26lt;%26lt; endl;





Otherwise you are going to just repeat the last element of your array the same number of times as the length of that array. So if you have three elements in the array you are going to repeat the item at Ginfo[num] three times. You need to use "i"





That should fix things up for you. Good luck!

printable cards

No comments:

Post a Comment