# Thread: I would like to get some help about String Array

1. ## I would like to get some help about String Array

Code:
```#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <math.h>

#define MAX_COLOURS 12

void prompt();
void choice();
void help();
void resistanceCal();

int first[12] = {0,1,2,3,4,5,6,7,8,9};
int second[12]= {0,1,2,3,4,5,6,7,8,9};
char third[][6] = {"10^0 ","10^1 ","10^2 ","10^3 ","10^4 ","10^5 ","10^6 ","10^7 ","10^8 ","10^9 ","10^-1","10^-2"};
int fourth[] ={0,0,0,0,0,0,0,0,0,0,5,10};
float thirdbandCal[] = {1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000,0.1,0.01};

char* colourCompare [] = {
"Black ",
"Brown ",
"Red   ",
"Orange",
"Yellow",
"Green ",
"Blue  ",
"Violet",
"Gray  ",
"White ",
"Gold  ",
"Silver"};

int main()
{
choice();

return 0;
}

void prompt()
{
printf("  1. Calculate resistance value\n  2. Help\n  3. Exit\n");

}

void help()
{
int index;
int len = 12;
system("cls");
printf("\t\t\t   Welcome to &HELP& section\n");
printf("This section helps user to understand the concept of the resister calculations.\n\n");

printf("\t\t      Table. Resistor colour code values\n");
printf("_____________________________________________________________________________\n");
printf("Colour   1st band   2nd band   3rd band(M,multiplier)   4th band(T,tolerance)\n");

for(index = 0; index < len; index++)
{
printf("%s      %d          %d               x%s                  +-%d%%\n",colourCompare[index],first[index],second[index],third[index],fourth[index]);

}
printf("_____________________________________________________________________________\n");
printf("\t CAUTION!! (0 represents NULL except Black 1st and 2nd bands 0's)\n");
printf("\n");

printf("For the 4 band code, the first two bands encode the first two significant digitsof the resistance value, ");
printf("the third is a power-of-ten multiplier or \nnumber-of-zeroes, and the fourth is the tolerance accuracy,");
printf("or acceptable error, of the value. The table below shows the meaning of each band colour.\n");
printf("For example,if the first band is red,the second is yellow,the third is orange,  and the fourth is gold,the resistor has a value of 24*10^3 +- 0.05*24*10^3 Ohm, or 24+-1.2 kOhm\n\n");

printf("Press any key to clear the console\n");
getch();
system("cls");

}

void choice()
{
int choice, flag = 1;

while (flag == 1)
{
prompt();
scanf("%d",&choice);
printf("\n");

if (choice == 1)
{
system("cls");
printf("\t\t\t&&Resistance Calculator&&\n\n");
resistanceCal();
flag = 1;
}
else if (choice == 2)
{
help();
flag = 1;
}
else if (choice == 3)
{
flag = 0;
}
else
{
flag = 1;
printf("Press any key to clear the console");
getch();
system("cls");
}
}
}

void resistanceCal()
{

char first[7],second[7],third[7],four[7];
int i,fi,se,th,fo,flag;
float integer,tolerance;

char* sign[4] = {"Ohm", "Kilo Ohm", "Mega Ohm", "Giga Ohm"};

printf("  Please type the first letter with UPPER CASE and rest for LOWER CASE\n\n");
getchar();

while(flag)
{

printf("What is the colour of the 1st band? :");
fgets(first,sizeof(first),stdin);
printf("\n");

for (i = 0;i<MAX_COLOURS;i++)
{

if (strcmp(first,colourCompare[i]) == 0)
{
flag = 0;
fi = i;
break;
}
else
{
flag = 1;
}
}

if(flag == 1)
{
}
}
getchar();

while(flag == 0)
{

printf("What is the colour of the 2nd band? :");
fgets(second,sizeof(second),stdin);
printf("\n");

for (i = 0;i<MAX_COLOURS;i++)
{

if (strcmp(second,colourCompare[i]) == 0)
{
flag = 1;
se = i;
break;
}
else
{
flag = 0;
}
}

if(flag == 0)
{
}
}

getchar();

while(flag == 1)
{

printf("What is the colour of the 3rd band? :");
fgets(third,sizeof(third),stdin);
printf("\n");

for (i = 0;i<MAX_COLOURS;i++)
{

if (strcmp(third,colourCompare[i]) == 0)
{
flag = 0;
th = i;
break;
}
else
{
flag = 1;
}
}

if(flag == 1)
{
}
}

getchar();

while(flag == 0)
{

printf("What is the colour of the 4th band? :");
fgets(four,sizeof(four),stdin);
printf("\n");

for (i = 0;i<MAX_COLOURS;i++)
{

if (strcmp(four,colourCompare[i]) == 0)
{
flag = 1;
fo = i;
break;
}
else
{
flag = 0;
}
}

if(flag == 0)
{
}
}
getchar();

float error = fourth[fo]/100.0;
integer = (fi*10 + se)*thirdbandCal[th];
tolerance = integer*error;

float sign1 = integer/1000;
float sign2 = sign1/1000;
float sign3 = sign2/1000;
float sign4 = tolerance/1000;
float sign5 = sign4/1000;
float sign6 = sign5/1000;

if((sign3 >= 1.0) && (sign6 >= 0.0))
{
printf("The resistance value is : %0.1f +- %0.1f %s\n\n",sign3,sign6,sign[3]);
}

else if((sign2 >= 1.0) && (sign5 >= 0.0))
{
printf("The resistance value is : %0.1f +- %0.1f %s\n\n",sign2,sign5,sign[2]);
}

else if((sign1 >= 1.0) && (sign4 >= 0.0))
{
printf("The resistance value is : %0.1f +- %0.1f %s\n\n",sign1,sign4,sign[1]);
}
else
{
printf("The resistance value is : %0.1f +- %0.1f %s\n\n",integer,tolerance,sign[0]);
}

printf("Press any key to clear the console.\n");
getch();
system("cls");

}```
This program is working almost fine. However, when it comes to fgets() part, it goes wrong. I've set my input array to 7 because the maximum length of the colour is 6. In this case, whenever the input character is 5, such as Black, then I have to type Black itself and space afterwards. ("Black " <- like this). Could anyone help me with this problem?

2. fgets leaves a \n on the end of the string.

You can either put a \n on the end of your strings you are searching for, or use strchr to find and replace the \n with a \0.

(laserlight has a good way of doing this, but I can't remember how she did it...)

3. I would recommend removing the new line for two reasons. First, it's probably semantically more accurate. You are likely not searching for a string containing a new line, so it should not be in the search pattern. Second, you would have to deal with ensuring you have enough space to append a new line on the end of the strings being searched and still have room for the null terminator, which is probably more prone to an off-by-one error or unterminated string (resulting in a buffer overflow) than removing a character from a string.

laserlight's method is probably the same as the one in the FAQ, which is a common idiom to strip a trailing new line: FAQ > Get a line of text from the user/keyboard (C) - Cprogramming.com.

The pertinent lines are these:
Code:
```if ((p = strchr(buf, '\n')) != NULL)
*p = '\0';```

4. Thank you very much!! I've tried it and it's fully working!!
If you have a time, could you tell me any techniques to reduce the code lines? (I mean, the way to simplify the codes)

5. By the way, what do you mean by removing the new line?

6. Originally Posted by tosihiro2007
By the way, what do you mean by removing the new line?
When you enter the color of the band, you press enter. That enter inserts a new line into the input buffer, so the string you entered looks like "Blue\n". Since your colourCompare array doesn't have that string, it will appear as though the color is invalid. But really, it is valid, you just don't want the new line. Note, you also want to remove the trailing spaces from colourCompare, otherwise the user has to input the right number of spaces after the color name for the comparison to work. So do this:
Code:
```char* colourCompare [MAX_COLOURS] = {  // giving an explicit size will allow the compiler to warn you if you have too few/many colors here -- enable the right warnings for your compiler if you want this
"Black",
"Brown",
"Red",
"Orange",
"Yellow",
"Green",
"Blue",
"Violet",
"Gray",
"White",
"Gold",
"Silver"
};
...
char *p;
...
if (fgets(one, sizeof(one), stdin) == NULL) {
// error with fgets, print a message and react appropriately
}
else {
p = strchr(one, '\n');  // look for a new line in one
if (p != NULL)  // found a new line, p points to it's location in the string
*p = '\0';  // "trim" it by replacing it with a null byte
}```

7. First things first, work on better indentation. Your code is hard to read, which means it's easy to make mistakes but hard to find and fix them.
Originally Posted by tosihiro2007
Thank you very much!! I've tried it and it's fully working!!
If you have a time, could you tell me any techniques to reduce the code lines? (I mean, the way to simplify the codes)
The biggest thing I see is that your input for the four color bands are essentially the same, the only difference is the '1st', '2nd', etc and the buffer you read input into. Whenever you find your self writing a piece of code very similar to another one you wrote, you should strongly consider making it a function. For example:
Code:
```void getColourBand(char *buf, int max_buf, char *band_num)
{
// fill in this part to read input into buf, similar to what you do alread on lines 165-195
}

// you call it like this:
getColourBand(one, sizeof(one), "1st");
getColourBand(two, sizeof(two), "2nd");
getColourBand(three, sizeof(three), "3rd");
getColourBand(four, sizeof(four), "4th");```
That should reduce lines 165-304 from ~140 lines down to about 35.

8. Thank you very much for your help guys!
From next time, I'm gonna make my program easy to read.

9. Just in case you are interested, it turns out that it was originally nominal Animal's method.

This is the method laserlight recommends
http://cboard.cprogramming.com/c-pro...-new-line.html