hi , just have a question here
if i use the function gets , to get an input such as
z 1234 5678 9011
how do i access to parts of the input
ie , i only want the "5678" bit ??
hi , just have a question here
if i use the function gets , to get an input such as
z 1234 5678 9011
how do i access to parts of the input
ie , i only want the "5678" bit ??
z 1234 5678 9011
| | | |
skip read read don't get to
Are you planning on using 5678 as an integer or a character string? If you want to use it as an int, then scanf would work better. You declare an int variable and scan in each letter or number accordingly and then discard it until you input something that you want to keep. scanf will overlook the z and read in 1234, then you do another scanf to the same variable and it will read in 5678.
Note that this only works on files where you know the layout of the information and it's consistent. And be sure not to use gets and scanf in the same program, I've gotten some nasty problesm from that.
If you really want to use gets though, you can read the entire line by using gets with \n as a termination condition, then use sscanf to put the characters that you want into a different string. You can ignore what you initially read into the first array and use what you put into the second array.
-Prelude
Last edited by Prelude; 09-13-2001 at 08:19 AM.
thanks for the help
i stored as char
what about
z 1234 5678 9011
if i only want "12" ???
Use gets and sscanf.
You can take any of the characters in the line in any combination and put them into another string with sscanf.
-Prelude
> Use gets and sscanf.
fgets and sscanf
never use gets - its a bug trap
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
huh?
what do i use then ? if i dun use gets?
This will do it nicely for you....
Code:char* newgets(char* buffer,int num) { int i; fgets(buffer,num,stdin); i=strlen(buffer)-1; if (buffer[i]=='\n') buffer[i]='\0'; return buffer; }
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi
> what do i use then ? if i dun use gets?
Already told you - use fgets
1. gets can only read from stdin, fgets can read from any FILE*
2. gets doesn't prevent buffer overflow, fgets does
3. the only difference between gets and fgets is that fgets adds the \n to the buffer.
4. sscanf doesn't care about \n, it treats it as whitespace
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.