Hey guys, I am pretty new to C. Is there anyway to use scanf to ignore letters and just read digits?
Would this be valid syntax within the scanf method:
scanf("%*[^0-9]d");
Hey guys, I am pretty new to C. Is there anyway to use scanf to ignore letters and just read digits?
Would this be valid syntax within the scanf method:
scanf("%*[^0-9]d");
Try the following ways,
orCode:scanf("%[0-9]s",&s); // Read only digits. scanf("%[^0-9\n]s", s); // Read other than digits up to newline.
Code:scanf(" %[^\n]", s); // read all whitespace, then store all characters up to a newline
Are those implementations reading and storing strings?
Yeah,it will seek the input from user by reading from standard input and stores the given value to the pointer specified as the second argument to scanf function which is given after the format specifier.
Actually, your syntax is wrong.
scanf("%*[^0-9]d");
Normally, If you used %d in scanf it will read only digits.
For Ex: If I give 123abc it will take only 123. But if you give abc123. It will take some garbage value.
And you are trying to use [ range ] in scanf.
It will also not suitable.
Note: [ range ] will not have any format characters. And it will read and store the value as string. It needs to specify like,
scanf("[^0-9]",s); // Correct
scanf("[^0-9]s",s); // Wrong
You can try some other way to read only integers.
Try,
* getchar() check whether the character is in 0-9 range.
And If you want to read and store integers try to use , getw() or fread() but this will be in binary text. not as like normal text. For more clarification read about "fread"
scanf() will not suitable for your requirement.
Thank you very much guys, you helped a lot. I have a better understanding now.
you actually missing %scanf("[^0-9]",s); // Correct
adding * you can avoid storing the string you want just skipCode:scanf("%[^0-9]",s); // Correct
And I suppose - as the above parsing should stop at the first digit - you can just add format for integer after thatCode:scanf("%*[^0-9]"); // Correct
Code:int n; scanf("%*[^0-9]%d", &n); // Correct
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler