GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 09-Nov-2006, 11:53
basketball749 basketball749 is offline
New Member
 
Join Date: Oct 2006
Posts: 9
basketball749 is on a distinguished road

Array/String question


Im having some trouble understanding array's and string's. I know that an string is a number of characters all put together but Im having trouble using them. I would like to have a 2D array and have a string from this array entered and scaned into the program(i can do this). However i would like to later call this string and assign the number of where it is in the array to it.

that might be kinda confusing so heres an example.
array[10][7] = {....................} (array's listed in brackets)
then i scan in a string from this array (ex. monday)
then in a later function i call the scaned in string but i get a number out of it (ex. 0-9)

thanks for any help
  #2  
Old 09-Nov-2006, 13:02
basketball749 basketball749 is offline
New Member
 
Join Date: Oct 2006
Posts: 9
basketball749 is on a distinguished road

Re: Array/String question


heres what i have so far

CPP / C++ / C Code:
*This program will evaluate the resistance of a resistor
*based on its color code.
*/
        
#include <stdio.h>
#include <math.h>
#include <string.h>
        
#define NOT_FOUND -1
        
int search(char arr[], char target, int num_str);
        
int
main(void)
{
        char again; /*y or n depending on user's desire to continue*/
        char band_1[7]; /*input- colors     */
        char band_2[7]; /*         of       */
        char band_3[7]; /*      three bands */
        char *color_codes[10][7] = {"black", "brown", "red", "orange", "yellow",
                                    "green", "blue", "violet", "gray", "white"};
        int ans; /*answer to the math done to find the resistance*/
        
   do {
        /*Prompt the user of what to do*/
        printf("Enter the colors of the resistor's three bands,\n");
        printf("beginning with the band nearest the end. Type the\n");
        printf("colors in lowercase letters only, NO CAPS.");
        
        /*User enters the three band colors*/
        printf("Band 1 => ");
scanf("%s, &band_1[7]");
        printf("Band 2 => ");
        scanf("%s, &band_2[7]");
        printf("Band 3 => ");
        scanf("%s, &band_3[7]");
        
        /*Search function that returns the subscript of the list element that matches
         *the target or returns -1*/

        int search(char arr[], char target, int num_str)

        /*Return resistance value*/

        
        printf("Resistance value: %d", search(band_1[7], band_2[7], band_3[7]);
        
      }
        /*Decode another resistor?*/
printf("\nDo you want to decode another resistor? (y/n)>");
        scanf(" %c", &again);
      } while (again == 'y' || again == 'Y');
        
return(0);
        
}
         
int search(char arr[], char target, int num_str)
        
int a   /*number corresponding to first color*/
int b   /*number corresponding to second color*/
int c   /*number corresponding to thrid color*/
        
        scanf("

and as i said im having trouble with the search function and how to return the number 0-9 of the array. this is need to calculate the resistance
Last edited by LuciWiz : 09-Nov-2006 at 16:52. Reason: Please insert your C/C++ code between [cpp] & [/cpp] tags
  #3  
Old 09-Nov-2006, 14:29
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,893
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Array/String question


Quote:
Originally Posted by basketball749
I know that an string is a number of characters all put together


I'll reword it slightly:

In C there is no such thing as a "string" data type. C library functions need a pointer to char as arguments, and the name of an array of char used by itself (without the [] brackets) is treated as a pointer to char. Therefore, an array of char can hold a "string" used in C programs.

In order to use functions such as strcpy(), strcat, etc, the contents of the array will be a zero-terminated sequence of chars.

In C there is such a thing as a "string literal". This is denoted by enclosing something in quote marks. The string literal is treated as a pointer to char, and the value of the pointer is the address somewhere in program data space of the first character of the "string". Therefore string literals can be used as arguments to string functions (but note that you can read from a string literal but you shouldn't try to write to it).

We can declare an array of pointers to char, and initialize it so that each element of the array has a value that points to a string literal.

In the following example, the array names is an array of pointers, and it is initialized to some specific things.

Therefore, things like names[0], names[1], etc. can be used as arguments to the various string functions (printf("%s"), strcpy, etc). And the array can be considered to be an array of constant "strings".

An example:

CPP / C++ / C Code:
#include <stdio.h>
#include <string.h>

int main()
{
   char *names[3] = {"Dave",     /* Gives a value to  names[0] */
                     "Zaphod",   /* Gives a value to names[1] */
                     "James"     /* Gives a value to names[2] */
                    };

   int i;

   for (i = 0; i < 3; i++) {
       printf("names[%d] = %s\n", i, names[i]);
   }

   return 0;
}

Output:
Code:
names[0] = Dave names[1] = Zaphod names[2] = James

Another example, that searches for a name among the crew members:

CPP / C++ / C Code:
#include <stdio.h>
#include <string.h>

int main()
{
   char *names[3] = {"Dave",     /* Gives a value to names[0] */
                     "Zaphod",   /* Gives a value to names[1] */
                     "James"     /* Gives a value to names[2] */
                    };

   char searchname[20] = {0};
   int i;

   for (i = 0; i < 3; i++) {
       printf("names[%d] = %s\n", i, names[i]);
   }

   printf("Enter a name to search for: ");
   scanf("%19s", searchname);
   for (i = 0; i < 3; i++) {
       if (strcmp(searchname, names[i]) == 0) {
           printf("%s is crew member number %d\n", searchname, i);
           break;
       }
   }
   if (i == 3) {/* got all of the way through the loop with no joy */
       printf("%s is not a crew member\n", searchname);
   }

   
   return 0;
}

Output
Code:
names[0] = Dave names[1] = Zaphod names[2] = James Enter a name to search for: Zaphod Zaphod is crew member number 1 . . . names[0] = Dave names[1] = Zaphod names[2] = James Enter a name to search for: Jean-Luc Jean-Luc is not a crew member

Note that to use scanf to get a "string", you give the address of the first element of the array. When you use the name of an array without the "[]" brackets, it is treated as pointer whose value is the address of the first element of the array.

Regards,

Dave
  #4  
Old 09-Nov-2006, 15:13
basketball749 basketball749 is offline
New Member
 
Join Date: Oct 2006
Posts: 9
basketball749 is on a distinguished road

Re: Array/String question


thanks for clarifying what a string and array exactly are. however, im still having some problems with the search. i understand what you said but with my program i would like to enter multiple strings and from each string return a subscript of the list element and use these numbers to do math.

ex(number returned for first string: 2
number returned for second string: 4
number returned for third string:1

2+4+1=7)

or something to that extent


ive revised my previous code and it collets the colors but does not produce an answer

CPP / C++ / C Code:
*This program will evaluate the resistance of a resistor
*based on its color code.
*/

#include <stdio.h>
#include <math.h>
#include <string.h>
        
        
int search (const char arr[], int target, int n);
        
int
main(void)
{
        char again; /*y or n depending on user's desire to continue*/
        char band_1[7]; /*input- colors     */
        char band_2[7]; /*         of       */
        char band_3[7]; /*      three bands */
        char *color_codes[7][10] = {"black", "brown", "red", "orange", "yellow",
                                    "green", "blue", "violet", "gray", "white"};
        int ans; /*answer to the math done to find the resistance*/

   do {
        /*Prompt the user of what to do*/
        printf("Enter the colors of the resistor's three bands,\n");
        printf("beginning with the band nearest the end. Type the\n");
        printf("colors in lowercase letters only, NO CAPS.\n");

        /*User enters the three band colors*/
        printf("Band 1 => ");
        scanf("%s", band_1); 
printf("Band 2 => ");
        scanf("%s", band_2);
        printf("Band 3 => ");
        scanf("%s", band_3);
        
        /*Search function that returns the subscript of the list element that matches
         *the target or returns -1*/
        

   
        /*Return resistance value*/
        
        printf("Resistance value: %d", ans);
        

        /*Decode another resistor?*/
        printf("\nDo you want to decode another resistor? (y/n)>");
        scanf(" %c", &again);
} while (again == 'y' || again == 'Y');
                   
return(0);
                   
}
        
#define NOT_FOUND -1
        
int search(const char arr[], int target, int n)/*array to search, value searched for, number of elements to search*/
        
{
        int i,
            found = 0 ,
            where;

        /*compares each element to target*/
        i = 0;
        while (!found && i < n) {
if (arr[i] == target)
                   found = 1;
            else
                   ++i;
        }
        
        /* Returns index of element matching target or NOT_FOUND */
        if (found)
                where = i;
        else
                where = NOT_FOUND;
        
        return (where);
}
Last edited by LuciWiz : 09-Nov-2006 at 16:52. Reason: Please insert your C/C++ code between [cpp] & [/cpp] tags
  #5  
Old 09-Nov-2006, 15:49
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,893
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Array/String question


Quote:
Originally Posted by basketball749
thanks for clarifying what a string and array exactly are.

With my example, your array would look like this:

CPP / C++ / C Code:
    char *color_codes[10]=    { "black", "brown", "red", "orange", "yellow",
                                "green", "blue", "violet", "gray", "white"
                               };

If you want a 2-D array of chars instead of an array of pointers to char, you could have this:

CPP / C++ / C Code:
    char color_codes[10][7]=  { "black", "brown", "red", "orange", "yellow",
                                "green", "blue", "violet", "gray", "white"
                               };

I didn't cover this, but what it does is the following:
1. It allocates memory for a 2-D array of char.
2. It initializes the "rows" of the array as follows:


It copies the string literal "black" to row number 0 of the array
It copies the string literal "brown" to row number 1 of the array
etc.

Now you could use either one and your program would work. It will not work with the way you declared the array, since you had a 2-D array of pointers. Not useful for this program.

Note that, for either of the two ways that I suggested, the notation for the rest of the program would be not identical, but either way could be used.

The second method would allow you to change the "strings" in the array contents if the program required it, but either way would work in your program.

I would put in a print statement for debugging purposes, just to make sure that the array is initialized properly.

CPP / C++ / C Code:
    int i;
.
.
.
    char *color_codes[10]=    { "black", "brown", "red", "orange", "yellow",
                                "green", "blue", "violet", "gray", "white"
                               };
.
.
.
        for (i = 0; i < 10; i++) {
            printf("color_codes[%d] = %s\n", i, color_codes[i]);
        }
        printf("\n");

Quote:
Originally Posted by basketball749
i would like to enter multiple strings and from each string return a subscript of the list element and use these numbers to do math

So, define a search function that takes a string as an argument (since the user enters a string) as well as the array and the count. Have the search function return the index of the color that the user entered.

Call the function three times; once for each color band.
Do the arithmetic on the three values that were returned:

CPP / C++ / C Code:
int search(char *arr[], char target[], int n);

int main()
{

.
.
.
    int value1, value2, value3;
.
.
.        /* get user input for the strings band_1, band_2, and band_3 */

        value1 = search(color_codes, band_1, 10);
        printf("value1 = %d\n", value1);

        value2 = search(color_codes, band_2, 20);
        printf("value2 = %d\n", value2);

        value3 = search(color_codes, band_3, 30);
        printf("value3 = %d\n", value3);
.
.
.

Now, use strcmp() in your search program to detect a match between the user entry and members of the array.

You should be able to get something like:

Code:
color_codes[0] = black color_codes[1] = brown color_codes[2] = red color_codes[3] = orange color_codes[4] = yellow color_codes[5] = green color_codes[6] = blue color_codes[7] = violet color_codes[8] = gray color_codes[9] = white Enter the colors of the resistor's three bands, beginning with the band nearest the end. Type the colors in lowercase letters only, NO CAPS. Band 1 => blue Band 2 => gray Band 3 => yellow value1 = 6 value2 = 8 value3 = 4 Resistance value: 680000

If you want a single function that calculates the value, then give it the three user strings as arguments (as well as the array name and size). That function will call the search() function three times and do the math on the returned values.

Of course, you could take out the extra print statements after debugging was complete.

Regards,

Dave
  #6  
Old 09-Nov-2006, 19:01
basketball749 basketball749 is offline
New Member
 
Join Date: Oct 2006
Posts: 9
basketball749 is on a distinguished road

Re: Array/String question


thanks for all your help by the way.

now ive updated it and put in strcmp but it now doesnt compile due to "the passing of arguement 1 of 'search' from incompatable pointer type". i thought i had all the pointers defnined tho.

heres the revised version

CPP / C++ / C Code:
int search (const char *arr1[], char target1[], int n1,
            const char *arr2[], char target2[], int n2,
            const char *arr3[], char target3[], int n3);
        
int
main(void)
{
        char again; /*y or n depending on user's desire to continue*/
        char band_1[7]; /*input- colors     */
        char band_2[7]; /*         of       */
        char band_3[7]; /*      three bands */
        char *color_codes[10] = {"black", "brown", "red", "orange", "yellow",
                                    "green", "blue", "violet", "gray", "white"};
        int value1, value2, value3;
        int ans; /*answer to the math done to find the resistance*/
        
   do { 
        /*Prompt the user of what to do*/
        printf("Enter the colors of the resistor's three bands,\n");
        printf("beginning with the band nearest the end. Type the\n");
        printf("colors in lowercase letters only, NO CAPS.\n");
        
        /*User enters the three band colors*/
        printf("Band 1 => ");
scanf("%s", band_1);
        printf("Band 2 => ");
        scanf("%s", band_2);
        printf("Band 3 => ");
        scanf("%s", band_3);
        
        value1 = search(color_codes, band_1, 10);
        printf("value1 = %d\n", value1);
        
        value2 = search(color_codes, band_2, 20);
        printf("value2 = %d\n", value2);
   
        value3 = search(color_codes, band_3, 30);
        printf("value3 = %d\n", value3);
        
        
        /*Search function that returns the subscript of the list element that matches
         *the target or returns -1*/
/*Return resistance value*/
        ans = value1*value2*(pow(10, value3));
        printf("Resistance value: %d", ans);
        
        
        /*Decode another resistor?*/
        printf("\nDo you want to decode another resistor? (y/n)>");
        scanf(" %c", &again);
      } while (again == 'y' || again == 'Y');
   
return(0);
        
}       
        
#define NOT_FOUND -1
         
int search(const char *arr1[], char target1[], int n1,
const char *arr2[], char target2[], int n2,
           const char *arr3[], char target3[], int n3)
        
{
        
        int i,
            found = 0 ,
            where;
        char *color_codes[10]= {"black", "brown", "red", "orange", "yellow",
                                "green", "blue", "violet", "gray", "white"
                                };
   
        /*compares each element to target*/
        i = 0;
        while (!found && i < n) {
            if (strcmp(arr[i], target) == 0)
                   found = 1;
            else
                   ++i;
}
           
        for (i = 0; i < 10; i++) {
            printf("color_codes[%d] = %s\n", i, color_codes[i]);
        }
        printf("\n");
            
            
        /* Returns index of element matching target or NOT_FOUND */
        if (found)
                where = i;
        else
                where = NOT_FOUND;
        
        
        return (where);
}
Last edited by admin II : 10-Nov-2006 at 05:24. Reason: Please insert your C/C++ code between [cpp] & [/cpp] tags
  #7  
Old 10-Nov-2006, 08:57
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,893
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Array/String question


Quote:
Originally Posted by basketball749

due to "the passing of arguement 1 of 'search' from incompatable pointer type

CPP / C++ / C Code:
int search (const char *arr1[], char target1[], int n1,
            const char *arr2[], char target2[], int n2,
            const char *arr3[], char target3[], int n3);
        
.
.
.
        char *color_codes[10] = {"black", "brown", "red", "orange", "yellow",

}


So change the variable type declaration for color_codes to match the argument type. If you are compiling this as a C program the message should be a warning, not an error.

On the other hand there are errors:

When you call a function, you must have an argument for every function parameter. The function definition has nine arguments. You call it three times with three arguments each time. That doesn't compute.

Also the function itself uses something called "target", but there is no argument named "target". The function looks up one value in a table. Look at the code and think about what the code is supposed to do. Then make it do it.

Regards,

Dave
 
 

Recent GIDBlogStupid Management Policies by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Borland compile question monnick C++ Forum 4 12-Feb-2006 18:40
non-member function question crq C++ Forum 1 03-Feb-2005 22:59
Simple question on arrays--please help! brookeville C++ Forum 16 18-Nov-2004 00:23
Repetition structure problem and question brookeville C++ Forum 17 29-Oct-2004 18:48
question of practice magiccreative C++ Forum 1 06-Feb-2004 08:17

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 00:14.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.