- This topic has 2 replies, 3 voices, and was last updated 14 years, 6 months ago by .
Viewing 2 reply threads
Viewing 2 reply threads
- The forum ‘C Programming’ is closed to new topics and replies.
Home › Forums › C Programming › Reading input string
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,
Nathan
Edit – 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<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 /> } |
To compare to strings I would use strcmp() from string.h , check out this link:
http://www.cplusplus.com/reference/clibrary/cstring/strcmp.html
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 be
Kindly wirite specific problem