![]() |
| | #1 |
| Registered User Join Date: Apr 2008
Posts: 87
| String parsing Code: #include <stdio.h>
#include <string.h>
int main(void)
{
char s[50];
int i = 0;
gets(s);
while (isspace(s[i]))
i++;
while (isdigit(s[i]))
i++;
while (isspace(s[i]))
i++;
if (s[i] != '\0')
printf("\nstring can't be converted\n");
return (0);
}
1234 78 1234 is not returned but an error message will be printed. Because a string should only contain 1 number I'm also working on a function for doubles i.e. representing them in exponential format. Last edited by broli86; 07-03-2008 at 12:54 PM. |
| broli86 is offline | |
| | #2 | |
| The larch Join Date: May 2006
Posts: 3,222
| I'm not very experienced with C string conversion functions, but from the references it seems that strtoul can already tell you that: Code: char* end;
num = strtoul(str, &end, 10);
//if *end is not 0 then there are unconsumed characters in str
if (*end != '\0')
So altogether the conversion function might look like this: Code: int smart_to_ulong(const char* str, unsigned long* num)
{
char* end = str;
//strtoul apparently doesn't report errors on negative values
if (!isdigit(str[0])) {
return 0;
}
errno = 0;
*num = strtoul(str, &end, 10);
//not read to the end
if (*end != '\0') {
return 0;
}
//over-flow
if (errno == ERANGE) {
return 0;
}
return 1;
}
__________________ I might be wrong. Quote:
Last edited by anon; 07-03-2008 at 01:28 PM. | |
| anon is offline | |
| | #3 | |
| Registered User Join Date: Apr 2008
Posts: 87
| Quote:
Last edited by broli86; 07-03-2008 at 04:07 PM. | |
| broli86 is offline | |
| | #4 | |
| The larch Join Date: May 2006
Posts: 3,222
| Ok, I added some of your logic to allow leading and trailing spaces and fixed a bug: unary + should be allowed before the number. Code: int smart_to_ulong(const char* str, unsigned long* num)
{
char* end = str;
//advance pointer past leading spaces
while (isspace(*str))
++str;
if (!*str) //must not end of string
return 0;
//strtoul apparently doesn't report errors on negative values
if (*str == '-') {
return 0;
}
errno = 0;
*num = strtoul(str, &end, 10);
//trailing spaces allowed
while (isspace(*end))
++end;
if (*end) { //must be end of string
return 0;
}
//over-flow
if (errno == ERANGE) {
return 0;
}
return 1;
}
__________________ I might be wrong. Quote:
| |
| anon is offline | |
![]() |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| char Handling, probably typical newbie stuff | Neolyth | C Programming | 16 | 06-21-2009 04:05 AM |
| Message class ** Need help befor 12am tonight** | TransformedBG | C++ Programming | 1 | 11-29-2006 11:03 PM |
| String editor for a sentence inputted by a user - any suggestions or ideas? | the_newbug | C Programming | 4 | 03-03-2006 02:11 AM |
| creating class, and linking files | JCK | C++ Programming | 12 | 12-08-2002 02:45 PM |
| Warnings, warnings, warnings? | spentdome | C Programming | 25 | 05-27-2002 06:49 PM |