473,395 Members | 1,578 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

how to I check a string in "if" loops??

hi
I got a simple program, and I was wondering how do you check if the
string in an array = a string. For example if I put "APPLE" in array
Array[10] then how can I check it with a if statement.

if (Array[ ] == 'APPLE'){
do something;
}

or do I need to use a different method to check?
Thanks
Chris

May 20 '07 #1
9 2819
<ch****@gmail.comwrote:
I got a simple program, and I was wondering how do you check if the
string in an array = a string. For example if I put "APPLE" in array
Array[10] then how can I check it with a if statement.

if (Array[ ] == 'APPLE'){
do something;
}

or do I need to use a different method to check?
That won't work. Use strcmp() in <string.h>
May 20 '07 #2
"ch****@gmail.com" <ch****@gmail.comwrites:
I got a simple program, and I was wondering how do you check if the
string in an array = a string. For example if I put "APPLE" in array
Array[10] then how can I check it with a if statement.
This is in the FAQ.

8.2: I'm checking a string to see if it matches a particular value.
Why isn't this code working?

char *string;
...
if(string == "value") {
/* string matches "value" */
...
}

A: Strings in C are represented as arrays of characters, and C
never manipulates (assigns, compares, etc.) arrays as a whole.
The == operator in the code fragment above compares two pointers
-- the value of the pointer variable string and a pointer to the
string literal "value" -- to see if they are equal, that is, if
they point to the same place. They probably don't, so the
comparison never succeeds.

To compare two strings, you generally use the library function
strcmp():

if(strcmp(string, "value") == 0) {
/* string matches "value" */
...
}

--
Comp-sci PhD expected before end of 2007
Seeking industrial or academic position *outside California* in 2008
May 20 '07 #3
On May 20, 8:47 pm, Ben Pfaff <b...@cs.stanford.eduwrote:
"chu...@gmail.com" <chu...@gmail.comwrites:
I got a simple program, and I was wondering how do you check if the
string in an array = a string. For example if I put "APPLE" in array
Array[10] then how can I check it with a if statement.

This is in the FAQ.

8.2: I'm checking a string to see if it matches a particular value.
Why isn't this code working?

char *string;
...
if(string == "value") {
/* string matches "value" */
...
}

A: Strings in C are represented as arrays of characters, and C
never manipulates (assigns, compares, etc.) arrays as a whole.
The == operator in the code fragment above compares two pointers
-- the value of the pointer variable string and a pointer to the
string literal "value" -- to see if they are equal, that is, if
they point to the same place. They probably don't, so the
comparison never succeeds.

To compare two strings, you generally use the library function
strcmp():

if(strcmp(string, "value") == 0) {
/* string matches "value" */
...
}

--
Comp-sci PhD expected before end of 2007
Seeking industrial or academic position *outside California* in 2008
Thanks for the help..I corrected my program as you told me, but I get
a small and irritating bug, when I compile the program it says:
trial2-1.c: In function 'co2':
trial2-1.c:18: error: parse error before ']' token

Here is the Source:

#include <stdio.h>

double co2(char fuel[], double amount){
double result;

//Petrol
if (strncmp(fuel[], "Car") == 0){
result = 2.3 * amount;
}

//Oil
else if (strncmp(fuel[], "Oil") == 0){
result = 2.7 * amount;
}

//Coal
else if (strncmp(fuel[], "Coal") == 0){
result = 2.4 * amount;
}

//Wood
else if (strncmp(fuel[], "Wood") == 0){
result = 0 * amount;
}

//Electricity
else if (strncmp(fuel[], "Electricity") == 0){
result = 0.4 * Amount;
}

//Natural Gas
else if (strncmp(fuel[], "Gas") == 0){
result = 0.2 * amount;
}

//Air Travel
else if (strncmp(fuel[], "Flight") == 0){
result = 0.3 * amount;
}

return result;
}
//Main program starts here
int main ()
{
char fuel[20];
double amount;
char desptn[40];
double total=0;
char answer;

FILE * fptr;
fptr = fopen("info.txt", "r");

//Displays the programs function
printf("\n\n");
printf("This program is designed to caculate the net CO2 emissions
\n");
printf("- Using the information listed in a file\n");
printf("- Read and analyse the information\n");
printf("- Give total CO2 emission in kg and 'rations'\n");
printf("- Provide a breakdown of the emissions\n");
printf("- Make use of the 'srncmp' function\n\n");

//Continue program?
printf("Do you what to start the program?(Y/N) ");
scanf(" %c",&answer);
printf("Reading File...\n\n\n");

//If Yes?
if(answer == 'Y' || answer == 'y'){
if (fptr == NULL ){
printf("Cannot Locate File, Please Try again!\n");
printf("Quitting...");
}
while (fscanf(fptr,"%19s %lf %39[^\n]",fuel , &amount, desptn) !=
EOF){
printf("%s \t %.2lf \t %s", fuel, amount, desptn);
printf("\n");
total += co2(fuel,amount);
}
}

printf("The total CO2 emission in kg: %.2lf kg", total);
printf("\n");
printf("Equicalent number of CO2 'rations': %.2lf", total = total /
2500);
printf("\nEnd Program!\n\n");
fclose(fptr);
return 0;
}

Thanks
Chris

May 20 '07 #4
On May 20, 8:47 pm, Ben Pfaff <b...@cs.stanford.eduwrote:
"chu...@gmail.com" <chu...@gmail.comwrites:
I got a simple program, and I was wondering how do you check if the
string in an array = a string. For example if I put "APPLE" in array
Array[10] then how can I check it with a if statement.

This is in the FAQ.

8.2: I'm checking a string to see if it matches a particular value.
Why isn't this code working?

char *string;
...
if(string == "value") {
/* string matches "value" */
...
}

A: Strings in C are represented as arrays of characters, and C
never manipulates (assigns, compares, etc.) arrays as a whole.
The == operator in the code fragment above compares two pointers
-- the value of the pointer variable string and a pointer to the
string literal "value" -- to see if they are equal, that is, if
they point to the same place. They probably don't, so the
comparison never succeeds.

To compare two strings, you generally use the library function
strcmp():

if(strcmp(string, "value") == 0) {
/* string matches "value" */
...
}

--
Comp-sci PhD expected before end of 2007
Seeking industrial or academic position *outside California* in 2008
Thanks for the help..I corrected my program as you told me, but I get
a small and irritating bug, when I compile the program it says:
trial2-1.c: In function 'co2':
trial2-1.c:18: error: parse error before ']' token

Here is the Source:

#include <stdio.h>

double co2(char fuel[], double amount){
double result;

//Petrol
if (strncmp(fuel[], "Car") == 0){
result = 2.3 * amount;
}

//Oil
else if (strncmp(fuel[], "Oil") == 0){
result = 2.7 * amount;
}

//Coal
else if (strncmp(fuel[], "Coal") == 0){
result = 2.4 * amount;
}

//Wood
else if (strncmp(fuel[], "Wood") == 0){
result = 0 * amount;
}

//Electricity
else if (strncmp(fuel[], "Electricity") == 0){
result = 0.4 * Amount;
}

//Natural Gas
else if (strncmp(fuel[], "Gas") == 0){
result = 0.2 * amount;
}

//Air Travel
else if (strncmp(fuel[], "Flight") == 0){
result = 0.3 * amount;
}

return result;
}
//Main program starts here
int main ()
{
char fuel[20];
double amount;
char desptn[40];
double total=0;
char answer;

FILE * fptr;
fptr = fopen("info.txt", "r");

//Displays the programs function
printf("\n\n");
printf("This program is designed to caculate the net CO2 emissions
\n");
printf("- Using the information listed in a file\n");
printf("- Read and analyse the information\n");
printf("- Give total CO2 emission in kg and 'rations'\n");
printf("- Provide a breakdown of the emissions\n");
printf("- Make use of the 'srncmp' function\n\n");

//Continue program?
printf("Do you what to start the program?(Y/N) ");
scanf(" %c",&answer);
printf("Reading File...\n\n\n");

//If Yes?
if(answer == 'Y' || answer == 'y'){
if (fptr == NULL ){
printf("Cannot Locate File, Please Try again!\n");
printf("Quitting...");
}
while (fscanf(fptr,"%19s %lf %39[^\n]",fuel , &amount, desptn) !=
EOF){
printf("%s \t %.2lf \t %s", fuel, amount, desptn);
printf("\n");
total += co2(fuel,amount);
}
}

printf("The total CO2 emission in kg: %.2lf kg", total);
printf("\n");
printf("Equicalent number of CO2 'rations': %.2lf", total = total /
2500);
printf("\nEnd Program!\n\n");
fclose(fptr);
return 0;
}

Thanks
Chris

May 20 '07 #5
"ch****@gmail.com" <ch****@gmail.comwrites:
Thanks for the help..I corrected my program as you told me, but I get
a small and irritating bug, when I compile the program it says:
trial2-1.c: In function 'co2':
trial2-1.c:18: error: parse error before ']' token

Here is the Source:

#include <stdio.h>
Add #include <string.hhere, at least.
double co2(char fuel[], double amount){
double result;

//Petrol
if (strncmp(fuel[], "Car") == 0){
Use strcmp not strncmp.
Use "fuel" not "fuel[]".
result = 2.3 * amount;
}
[...]
//Air Travel
else if (strncmp(fuel[], "Flight") == 0){
result = 0.3 * amount;
}
What if it isn't any of those?
return result;
}
//Main program starts here
It's really better to avoid silly comments like this.
Everyone knows that the main function is the main program.
int main ()
It's better to write "int main (void)" explicitly.
{
char fuel[20];
double amount;
char desptn[40];
double total=0;
char answer;

FILE * fptr;
fptr = fopen("info.txt", "r");
Should check for success here.
//Continue program?
printf("Do you what to start the program?(Y/N) ");
Do you "what"? :-)
scanf(" %c",&answer);
printf("Reading File...\n\n\n");

//If Yes?
if(answer == 'Y' || answer == 'y'){
if (fptr == NULL ){
printf("Cannot Locate File, Please Try again!\n");
printf("Quitting...");
}
Seems a little late to report that failure here. You knew it
would fail before user interaction started.
printf("Equicalent number of CO2 'rations': %.2lf", total = total /
2500);
It's not very nice for output to have unrelated side effects.
--
Comp-sci PhD expected before end of 2007
Seeking industrial or academic position *outside California* in 2008
May 20 '07 #6
ch****@gmail.com wrote:
>
Thanks for the help..I corrected my program as you told me, but I get
a small and irritating bug, when I compile the program it says:
trial2-1.c: In function 'co2':
trial2-1.c:18: error: parse error before ']' token

Here is the Source:

#include <stdio.h>

double co2(char fuel[], double amount){
double result;

//Petrol
if (strncmp(fuel[], "Car") == 0){
The empty [] after fuel is you problem. Remove them, empty [] are only
valid and required when declaring a function parameter type as an array.

--
Ian Collins.
May 20 '07 #7
Ben Pfaff wrote, On 20/05/07 20:47:
"ch****@gmail.com" <ch****@gmail.comwrites:
>I got a simple program, and I was wondering how do you check if the
string in an array = a string. For example if I put "APPLE" in array
Array[10] then how can I check it with a if statement.

This is in the FAQ.

8.2: I'm checking a string to see if it matches a particular value.
Why isn't this code working?
<snip>

To the OP, the FAQ is located at http://c-faq.com/ and should be checked
before posting questions here.
--
Flash Gordon
May 20 '07 #8
On May 20, 9:09 pm, Flash Gordon <s...@flash-gordon.me.ukwrote:
Ben Pfaff wrote, On 20/05/07 20:47:
"chu...@gmail.com" <chu...@gmail.comwrites:
I got a simple program, and I was wondering how do you check if the
string in an array = a string. For example if I put "APPLE" in array
Array[10] then how can I check it with a if statement.
This is in the FAQ.
8.2: I'm checking a string to see if it matches a particular value.
Why isn't this code working?

<snip>

To the OP, the FAQ is located athttp://c-faq.com/and should be checked
before posting questions here.
--
Flash Gordon
Thank....I got what I needed...I thank you all who answered my
question.

May 20 '07 #9
"ch****@gmail.com" wrote:
>
.... snip ...
>
Thanks for the help..I corrected my program as you told me, but I
get a small and irritating bug, when I compile the program it says:
trial2-1.c: In function 'co2':
trial2-1.c:18: error: parse error before ']' token

Here is the Source:

#include <stdio.h>

double co2(char fuel[], double amount){
double result;

//Petrol
if (strncmp(fuel[], "Car") == 0){
result = 2.3 * amount;
}
.... snip ...
>
//Air Travel
else if (strncmp(fuel[], "Flight") == 0){
result = 0.3 * amount;
}
return result;
}
Use strcmp(fuel, "Car"), not strncmp (which you are miscalling).
Be aware that you may return an undefined result value if no case
matches..

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
<http://kadaitcha.cx/vista/dogsbreakfast/index.html>
cbfalconer at maineline dot net

--
Posted via a free Usenet account from http://www.teranews.com

May 21 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

32
by: Nuno Paquete | last post by:
Hi group. I'm using this code to see if is there any parameter for variable "menu": if($_GET == "downloads") .... But this code log errors if there is no parameter passed (this heappens at...
3
by: Mark Sullivan | last post by:
When I trace through a csharp program I came to a situation where a certain values has an "undefined value" as shown in the debugger DbgClr. I want to check this but the following statements did...
4
by: Miguel Dias Moura | last post by:
Hello, i have this code line in a script in my ASP.net / VB web site: if msgNewsletterAction = "Go" Then code1 Else code2 End If
35
by: pinkfloydhomer | last post by:
How do I check if a string contains (can be converted to) an int? I want to do one thing if I am parsing and integer, and another if not. /David
37
by: jht5945 | last post by:
For example I wrote a function: function Func() { // do something } we can call it like: var obj = new Func(); // call it as a constructor or var result = Func(); // call it as...
30
by: Jess | last post by:
Hello, I tried a program as follows: include<iostream> using namespace std; class A{ public:
1
by: askoenig | last post by:
#1 How do I tell if I have "curl over ssl" installed? What specific "switch" or line of text do I look for in the result page from running phpinfo.php on my server? #2 "Curl over ssl" is NOT...
0
by: chutsu | last post by:
hi I got a simple program, and I was wondering how do you check if the string in an array = a string. For example if I put "APPLE" in array Array then how can I check it with a if statement. if...
6
by: stanleyhsieh | last post by:
Hi all! I'm new here! I was wondering how I can check if a string contains only "A-Za-z0-9_" and ".". I tried the following code function check_validstring($check_validstring) { ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.