hi
in my program's input is a string, but i actually do not know, what its size will be (
so i need somehow change the strings size on demand, i.e. my goal is let user type as many chars as he wants and save them all into 1 string
cheers
hi
in my program's input is a string, but i actually do not know, what its size will be (
so i need somehow change the strings size on demand, i.e. my goal is let user type as many chars as he wants and save them all into 1 string
cheers
Sort of a side questions, architecturally speaking, under *nix or Windows, what could be the longest string passed as an argument? And of the "should not use" gets(), what about it?
(Sorry to hijack, but perhaps (hopefully) still on topic.
Todd
You can use realloc() to continuously resize the buffer and allocate more memory for your char buffer.
*oilrg:
You could make a very large (512, 1024 maybe?) char array for the user's entry, then add the '\0', to elevate the char's to a single char string. The sizeof() function should be perfect to give you the actual size in bytes for your perfectly sized array.
Be sure to delete the large initial array, when you no longer need it, before leaving the function that creates it.
You'll find the tutorial section helpful. If you'll post up some code, and ask specific questions, then we can be more helpful, without needing to write a post which needs to be like a text book.
*Todd:
When you pass a string as an argument, and it's a large string, you would normally pass it as a pointer only, not the entire string. That way, size is not a problem.
The gets() function passes whatever is entered into it, regardless of it having exceeded the maximum limit of any kind. That can lead to huge problems, which can effect the stability of the system. The fgets() is the safe way to get input from a user, because you have to specify beforehand, what the size of the input, (maximum), will be.
Check the tutorial for all the details.
the code is smth like that:
input is 0..9 & a..b (not checks others)
counts the base of the 'number' (max 36 - 'z'), and writes down that 'number' is in decimal
Code:#include <stdio.h> #include <string.h> #include <math.h> int main() { char s[256]; int base=0,basemax=0,i; long decimalone=0; scanf("%s",&s); for (i=0;i<strlen(s);i++) { if (s[i]>=97) base=s[i]-86; else base=s[i]-47; if (base>basemax) basemax=base; } for (i=0;i<strlen(s);i++) { if (s[i]>=97) decimalone+=(s[i]-87)*pow(basemax,(strlen(s)-1-i)); else decimalone+=(s[i]-48)*pow(basemax,(strlen(s)-1-i)); } printf("\n\n%d",basemax); printf("\n\n%d",decimalone); return 0; }
Last edited by oilrg; 12-02-2007 at 03:04 AM.