I would like to enter a string such as "111111111111.....11111111" (50
ones),and then convert it to a
number(111111111111.....11111111),because I want to use that number to
do some additions.How can I do that?
The following is my trial,but I find that the "a" is always 0.
[hopeless code snipped]
Try this as a place to start. You will obviously want to modify it.
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stddef.h>
int main()
{
unsigned long long /* or unsigned long if you don't have
this type */
the_number = 0;
unsigned limit = CHAR_BIT * sizeof the_number;
char buffer[limit + 2], *endp, *nl;
ptrdiff_t nchars;
printf("Please type a binary number of at most %u digits.\n"
"A character other than 0 or 1 will terminate the number.\n"
"Remember to end your imput with an end-of-line character.\n"
"Type it here: ", limit);
fflush(stdout);
errno = 0;
if (!fgets(buffer, sizeof buffer, stdin)) {
fprintf(stderr,
"Something untoward happened with your input.\n");
if (errno)
perror("errno was set because:");
fprintf(stderr, "I'm giving up.\n");
exit(EXIT_FAILURE);
}
if ((nl = strchr(buffer, '\n')))
*nl = 0;
else
fprintf(stderr, "That was a very long line. The end-of-line\n"
"character never made it into the buffer,\n"
"The string we will be converting is:\n\"%s\"\n",
buffer);
the_number =
strtoull /* or strtoul, if needed */ (buffer, &endp, 2);
if (errno)
perror("errno was set:");
if (*endp) {
nchars = endp - buffer;
fprintf(stderr, "The string ended with %c (%d)\n"
"rather than an EOL character.\n", *endp, *endp);
*endp = 0;
printf("The string converted was %u chars, and was\n"
"\"%s\".\n", (unsigned) nchars, buffer);
}
printf
("Your number is %llu (base 10), %#llo (base 8), %#llx"
" (base 16)\n",
the_number, the_number, the_number);
return 0;
}