Home › Forums › C Programming › Reading input string
- This topic has 2 replies, 3 voices, and was last updated 16 years, 5 months ago by Adetutu.
- AuthorPosts
- May 31, 2008 at 9:59 pm #2105Arunkumar.NParticipant
Hello,
I’m pretty new to C so if you think i’m going about this completely wrong, please tell me so. I’ve looked through multiple tutorial sites, but im still not certain how i need to go about this. Basically what I am trying to do is create a periodic table program for the command line, first it draws a text only periodic table, then it asks the user to input the chemical symbol an element. What im wanting it to do is after it gets the input, is to go to a part in the program and print information about the element to the terminal. I just don’t know how to compare the strings, to the preset element symbols. I was thinking i would have to use either a If stament or switches? is there any way to do this, or am i taking the wrong approach? I’m sorry if i don’t make much sense right now.Thanks,
NathanEdit – I figgured out how to do what i was needing to do, so i’ll post a simple version of what a came up with. And i should probably give credit to http://www.cprogramming.com/ for the function to remove the null terminator.
12345678910111213141516171819202122232425262728293031323334<br />#include <stdio.h><br />#include <stdlib.h><br />#include <strings.h><br />void strip_newline( char *str, int size )<br />{<br />int i;<br />/* remove the null terminator */<br />for ( i = 0; i < size; ++i )<br />{<br />if ( str == 'n' )<br />{<br />str = ' ';<br /><br />/* we're done, so just exit the function by returning */<br />/* return; */<br />}<br />}<br />/* if we get all the way to here, there must not have been a newline! */<br />}<br />int main()<br />char symbol[50];<br />printf( "Please enter Chemical Symbol " );<br />fgets( symbol, 50, stdin );<br />system("cls");<br />/* see definition above */<br />strip_newline( symbol, 50 );<br />/* strcmp returns zero when the two strings are equal */<br />if ( strcmp ( symbol, "H" ) == 0 )<br />{<br />printf("hydrogen");<br />}<br />return 0;<br />} - June 2, 2008 at 10:53 am #3397HumayanParticipant
To compare to strings I would use strcmp() from string.h , check out this link:
http://www.cplusplus.com/reference/clibrary/cstring/strcmp.html
- July 10, 2008 at 4:37 am #3398AdetutuParticipant
Actually your code is right. However from your messgae it is not clear what the problem is?
Well check the herader file name. It must besecond opening curley braces ({) after main().
Kindly wirite specific problem
- AuthorPosts
- The forum ‘C Programming’ is closed to new topics and replies.