Question:
C Programming; How to convert str. to int from user input?
multiz_com
2007-05-11 12:55:50 UTC
I need to make 2 functions:
(1) I have: void getStr(char * str, int maxChars) ; and I need this function to get a string from user (without gets() and scanf()) using getchar(). "str" is the address to start writing characters, and "maxChars" is the maximum number of non-null characters that you can input – at that point you must stop putting characters into the string. The input also comes to an end when a newline is input.
(2) The 2nd is "int stringToInt(char * str)". This function reads in characters starting at the address stored in "str" until it either encounters a non-digit or null.
Thanks for any help!
Four answers:
polly_peptide
2007-05-11 13:06:07 UTC
You need to say what versions of everything you are using.



In .Net C# you can say this



int.TryParse(mystring, out myint);



and the method will return true if the parsing worked correctly. You will not write this function yourself unless you were asked to. Get it from the standard library - whichever one you are using.
2007-05-11 13:25:14 UTC
//This function parses the digit from character to int format.

int parseDigit(char* digit){

if(digit==null){

//check to see that digit is not null otherwise the program will terminate abnormally. -1 is returned if null is encountered.

return -1;

}else{//return the integer that symbolizes the character representation

if(*digit='1'){

return 1;

} // add code

}

}



int parseInt(char *str){

int temp=0;

while(str!=0){

//Store the digits to temp. note. float or double will not work like this.

temp = temp*10 + parseDigit(str++);

}

return temp;

}



This should solve ur purpose. Moreover look through the documentation. you will surely find a char[] to Integer conversion function.
Patrick G
2007-05-11 13:08:56 UTC
To convert string to int you could use a simple 10 statement match:



int i = 0 , j = 0;

int array[10];



i = sizeof(string)



while j < i

if string[j] == 1;

array[j] = 1;



etc for every number



then another function could access that array and loop like this

i = 0;

j = sizeof(int array)



while i +1< j

intarray[i] = int array [i]*10 + int array[i+1];



so if i the array is only 1 number it will skip the loop



just some thoughts from another beginner
?
2016-10-15 13:50:51 UTC
you could smash it down so as that your recurring methods the optimal maximum set bit and calls itself on each and every of the bits below it. That way it would fulfill the 'recursive' requirement.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...