Sunday, July 12, 2009

Strings and character arrays in C++?

I currently am having a problem regarding strings and character arrays. What I want to do is have a user type a string like "Johnson 5000" (using cin, not from an input file or preset string), and I want to store this input into two parallel arrays. One for characters while the other is for values. Assume that all variables are properly declared.





for (int canidateNum = 0; canidateNum %26lt; ROWS; canidateNum++)


{


cout %26lt;%26lt; "Canidate #" %26lt;%26lt; canidateNum + 1 %26lt;%26lt; ": ";


cin %26gt;%26gt; name[canidateNum] %26gt;%26gt; voteNum[canidateNum];


}


cout %26lt;%26lt; name[0] %26lt;%26lt; " " %26lt;%26lt; voteNum[0] %26lt;%26lt; endl;


...





However, upon entering something like "Johnson 5000" in the program, it will output the wrong result, displaying J and not 5000. I tried using various methods of inputing a string into a character array, but to no avail. I tried multi-dimensional arrays, but that didn't work for me either (probably did it wrong).





Can anyone assist me in this?

Strings and character arrays in C++?
Your array should be a string array.


A character array will only hold 1 character at each location.


Given that you are just storing the input in one location it is not surprising that it does not work.


If you still want a character array then it must have 2 dimensions. One for each candidate and one for each character of the input.


You then need to read your input one character at a time.
Reply:cout %26lt;%26lt; a[0]; would mean output the single character at the zero position.


cout %26lt;%26lt; a; should output the whole string.





char name[50];


cin %26gt;%26gt; name;


cout %26lt;%26lt; "Hello " %26lt;%26lt; name;





A string is an array of characters so if you want an array of strings your going to need an array of character arrays. array of array. Now I'm confused. Thank you.
Reply:How you declare your Arrays? correct way to declare an Array is





char name[20]; //string array to hold a name of 21 characters





or


char name[10][20]; /*2D string array to hold 11 names of 21 characters each/*





//to store names use use for loop


for(i=0;i%26lt;=10;i++)


cin%26gt;%26gt;name[i][];
Reply:Use a structure


typedef struct


{


char name[80];


long votes;


} candidate_type;





candidate_type candidate[ROWS];


for (int canidateNum = 0; canidateNum %26lt; ROWS; canidateNum++)


{


cout %26lt;%26lt; "Canidate #" %26lt;%26lt; canidateNum + 1 %26lt;%26lt; ": ";


cin %26gt;%26gt; candidate[canidateNum].name;


cin %26gt;%26gt; candidate[canidateNum].votes;


}


cout %26lt;%26lt; candidate[0].name %26lt;%26lt; " " %26lt;%26lt; candidate0].votes %26lt;%26lt; endl;

strawberry

No comments:

Post a Comment