I'm writing a code in C to find the digits that repeat in a given number, and the one that I wrote works fine for small numbers, but the output gets messed up if I input a large value, N < 1000.
Here is my code; please help me out!
For the input:
1839138012980192380192381090981839
I get this output:
0 2 3 5 7 8
#include <stdio.h>
int main()
{
int digit, digits[10], flag = 0, i;
long long num;
scanf("%lld", &num);
while (num)
{
digit = num % 10;
if (digits[digit])
flag = 1;
digits[digit]++;
num /= 10;
}
if (flag)
{
for (i = 0; i < 10; i++)
{
if (digits[i] > 1)
printf("%d ", i);
}
printf("\n");
}
else
printf("The are no repeated digits.\n");
return 0;
}
The long long type can only represent a limited range of numbers. In your C implementation, 1839138012980192380192381090981839 is too big for long long, and scanf("%lld", &num) does not work.
Instead, read each character of input using c = getchar();, where c is declared as an int. If, after getchar, c is EOF, stop looping and print the results. If c is not EOF, then check whether it is a digit using if (isdigit((unsigned char) c)). The isdigit function is defined in <ctype.h>, so include that header.
If the character is a digit, then convert it from a character to the number it represents using c - '0'. You can use int d = c - '0'; to store the number in d. Then increment the count for the digit d.
If the character is not a digit, you can decide what to do:
There will likely be a new-line character, '\n', at the end of the line the user entered. You may want to ignore it. When you see the new-line, you could end the loop and print the results, you could continue reading to see if there are any other digits or characters before EOF is seen and report a problem to the user if there are, or you could ignore it and continue looping.
There could be spaces in the input. You might want to ignore them, or you might want to report a problem to the user.
If there are other characters, you might want to report a problem to the user.
Here's another approach, which you could use with a string of some maximum length (defined by the constant MAX_LEN).
A string made up of a bunch of char will use one byte per character, so you can define MAX_LEN up to how many bytes you have in system memory, generally, although in practice you probably would use a much smaller and more reasonable number.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 12345
int main()
{
int digit, digits_checker[10] = {0}, flag = 0, i;
char* num;
/* set aside space for the string and its terminator */
num = malloc(MAX_LEN + 1);
/* read num from input */
scanf("%s", num);
/* get the string length */
size_t num_length = strlen(num);
/* walk over every character in num */
for (size_t position = 0; position < num_length; position++)
{
/*
We assume that the value of num[position] is an
ASCII character, from '0' to '9'. (If you can't make
that assumption, check the input and quit with an
error, if a non-digit character is found.)
If the input is valid, the digits 0-9 in the ASCII
table start at 48 ('0') and end at 57 ('9'). Subtracting
48, therefore, gives you the integer value at each digit
in num.
*/
digit = num[position] - 48;
/*
Increment a counter for each digit
*/
digits_checker[digit]++;
}
/* num is no longer needed, so we free its memory */
free(num);
/* check each digit */
for (i = 0; i < 10; i++)
{
if (digits_checker[i] > 1) {
printf("%d ", i);
flag = 1;
}
}
if (!flag) {
printf("The are no repeated digits.\n");
}
else {
printf("\n");
}
return 0;
}
The suggestion to check input is a good one. You can't necessarily assume that what someone enters will be entirely made up of digit characters.
But hopefully this demonstrates how to set aside space for a string, and how to read through it, one character at a time.
Related
I am currently on a beginner course in C and was given an exercise requiring my program to check if the user input contains non-alphabets. I've figured to use the function isalpha() to check the user input and if it contains non-alphabets, the program should ask the user to enter another input.
Below is my current code:
#include <stdio.h>
#include <ctype.h>
#define MAX 13
int main() {
char player1[MAX];
int k = 0;
// Ask player 1 to type a word.
printf("Player 1, enter a word of no more than 12 letters: \n");
fgets(player1, MAX, stdin);
// // Loop over the word entered by player1
for (int i = 0; i < player1[i]; i++) {
// if any chars looped through is not an alphabet, print message.
if (isalpha((unsigned char)player1[i]) == 0) {
printf("Sorry, the word must contain only English letters.");
}
}
However, after testing it, I've derived a few cases from its results.
Case 1:
Entering without any input prints ("Sorry, the word must contain only English letters. ")
Case 2:
An input with 1 non-alphabetic character prints the 'sorry' message twice. Additionally, an input with 2 non-alphabetic characters print the 'sorry' message thrice. This implies that case 1 is true, since no input prints the message once, then adding a non-alphabetic prints the message twice.
Case 3:
An input of less than 10 characters(all alphabetic) prints out the sorry message also.
Case 4:
An input of more than 9 characters(all alphabetic) does not print out the sorry message, which satisfies my requirements.
Why are these the cases? I only require the message to print once if after looping through the user input, there's found to be a non-alphabetic character!
As #unwind has noted, the conditional of the OP for() loop is incorrect.
Good to trust to isalpha() but your code doesn't have to fondle each and every character. Another standard library function, strspn(), when supplied with your needs, can perform the looping work for you.
#include <stdio.h>
#include <string.h>
#define MAX 12
int main() {
char player1[ MAX + 1 + 1 ]; // buffer size for fgets() 12 + '\n' + '\0'
char *permissible =
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Ask player 1 to type a word.
printf("Player 1, enter a word of no more than %d letters: \n", MAX);
fgets(player1, sizeof player1, stdin);
if( player1[ strspn( player1, permissible ) ] != '\n' )
printf("Sorry, the word must contain only English letters.");
return 0;
}
Strings in C are null-terminated, which means they contains an extra byte '\0' to mark the end of the string (character 0 in the ascii table), so you can only store 12 characters in a char array of size 13.
If you array contains a string smaller than 12 characters, since you loop over the whole array, you'll meet that null-terminating-byte, which fails isalpha(): it checks if character is in range ['A', 'Z'] or ['a', 'z']. Characters are just integers for your computers, so isalpha() checks if received value is is range [65, 90] or [97, 122], and 0 is not.
To be more precise, the notion of integer makes no sense for your computer, that's just how we interpret information, it's just a bunch of bits for your computer.
See ascii table: https://www.rapidtables.com/code/text/ascii-table.html
By having a fixed size buffer, you'll have garbage after the contained string if the string doesn't take all the space.
You have 2 conditions to stop iterating:
end of array, to prevent overflowing the array
end of string, to prevent mis-interpreting bytes in array which are further than string end
Error message might be printed several times, since you keep checking even after an error occured, you have to break the loop.
Below code doesn't meet mentioned problems
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define BUFFER_SIZE 13
#define MIN(a, b) (a < b ? a : b)
int main(void)
{
char player1[BUFFER_SIZE];
int maxIndex;
int i;
/* Ask player 1 to type a word */
printf("Player 1, enter a word of no more than 12 letters: \n");
fgets(player1, BUFFER_SIZE, stdin);
/*
* Max index for iteration, if string is lesser than 12 characters
* (excluding null-terminating byte '\0') stop on string end, otherwise
* loop over whole array
*/
maxIndex = MIN(strlen(player1) - 1, BUFFER_SIZE);
for (i = 0; i < maxIndex; i++) {
/* Print error if non-letters were entered */
if (isalpha(player1[i]) == 0) {
printf("Sorry, the word must contain only English letters.");
/* Error occured, no need to check further */
break;
}
}
/*
for (i = 0; i < maxIndex; i++)
printf("%d ", (int) player1[i]);
printf("\n%s\n", player1);*/
return 0;
}
The MIN() is a macro, a ternary expression which returns the smallest argument, nothing really complicated here.
But note that, when you enter the word, you press <Enter>, so your string contains a "go to next line" character (character '\n', n°10 in ascii table, as #Shawn mentioned in comments), so you have to stop before it: that's why I use strlen(player) - 1, string ends with "\n\0", and strlen() returns the number of bytes before '\0' (including '\n').
I've let a dump of the string at the end, you can modify the end-index there to see what's sent to isalpha(), replace maxIndex with BUFFER_SIZE.
This:
for (int i = 0; i < player1[i]; i++) {
loops from 0 up until (but not including) the code point value of the i:th character, updating i every time it loops. It will very likely access outside the array bounds, which is undefined behavior.
It should look for the terminator (or linefeed but let's keep it simple):
for (size_t i = 0; player1[i] != '\0'; ++i) {
to use the function isalpha() to check the user input and if it contains non-alphabets
Simply read one character at a time. No maximum needed.
#include <ctype.h>
#include <stdio.h>
int main(void) {
int ch;
int all_alpha = 1;
printf("Player 1, enter a line\n");
while ((ch = getchar()) != '\n' && ch != EOF) {
if (!isalpha(ch) {
all_alpha = 0;
}
}
if (!all_alpha) {
printf("Sorry, the line must contain only letters.");
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have to write a program that converts an user input (which is a string) to an Integer. In the same time it should check, if the user input really is a number.
And also everything in one method.
and NO LIBRARY FUNCTIONS allowed.
I can't figure any idea how to do it. All I got for the beginning is just this pathetic structure
#include <stdio.h>
void main()
{
char input[100];
int i;
int sum = 0;
printf("Type a String which will be converted to an Integer: ");
scanf("%c, &input");
for (i = 0; i < 100; i++)
{
}
}
I appreciate any help, thanks
The conversion is the easy part...
But if you must not use library functions,
there is only one way to take a string, and that is argv;
there is only one way to give an integer, and that is the exit code of the program.
So, without much ado:
int main( int argc, char * argv[] )
{
int rc = 0;
if ( argc == 2 ) // one, and only one parameter given
{
unsigned i = 0;
// C guarantees that '0'-'9' have consecutive values
while ( argv[1][i] >= '0' && argv[1][i] <= '9' )
{
rc *= 10;
rc += argv[1][i] - '0';
++i;
}
}
return rc;
}
I did not implement checking for '+' or '-', and did not come up with a way to signal "input is not a number". I also just stop parsing at the first non-digit. All this could probably be improved upon, but this should give you an idea of how to work around the "no library functions" restriction.
(Since this sounds like a homework, you should have to write some code of your own. I already gave you three big spoons of helping regarding argv, the '0'-'9', and the conversion itself.)
Call as:
<program name> <value>
(E.g. ./myprogram 28)
Check return code with (for Linux shell):
echo $?
On Windows it's something about echo %ERRORLEVEL% or somesuch... perhaps a helpful Windows user will drop a comment about this.
Source for the "'0'-'9' consecutive" claim: ISO/IEC 9899:1999 5.2.1 Character sets, paragraph 3:
In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.
I'm sure this is preserved in C11, but I only have the older C99 paper available.
Take hightes digit and add it to number, multiply the number by 10 and add the next digit. And so on:
#include <stdio.h> // scanf, printf
void main()
{
char input[100];
printf("Type a String which will be converted to an Integer: ");
scanf("%s", input);
int number = 0;
int neg = input[0] == '-';
int i = neg ? 1 : 0;
while ( input[i] >= '0' && input[i] <= '9' )
{
number *= 10; // multiply number by 10
number += input[i] - '0'; // convet ASCII '0'..'9' to digit 0..9 and add it to number
i ++; // step one digit forward
}
if ( neg )
number *= -1;
printf( "string %s -> number %d", input, number );
}
input[i] - '0' works, because ASCII characters '0'..'9' have ascending ASCII codes from 48 to 57.
So basically you want to know how something like the standard library atoi works. In order to do this, you need to consider how strings represent numbers.
Basically, a string (that represents a number) is a list o digits from 0 to 9. The string abcd (where a, b, c, d are placeholders for any digit) represents the number a*10 ^ 3 + b*10^2 + c * 10 + d (considering base 10 here, similar for other bases). So basically you need to decompose the string as shown above and perform the required arhitmetic operations:
// s - the string to convert
int result = 0;
for (int index = 0; index < strlen(s); index++) {
result = result * 10 + s[index] - '0';
}
The operation s[index] - '0' converts the character that represent a digit to its value.
// the function returns true for success , and false for failure
// the result is stored in result parameter
// nb: overflow not handled
int charToInt(char *buff,int *result){
*result=0;
char c;
while(c=*buff++){
if((c < '0') || (c >'9')) // accept only digits;
return 0;
*result *= 10;
*result += c-'0';
}
return 1;
}
Lot of things which are missed. Firstly taking a string in is done by scanf("%s",input); By the way in which you are receiving it, it only stores a character, secondly run the loop till the length of the string recieved. Check the below code.
#include <stdio.h>
#include<string.h>
void main()
{
char input[100];
int i;
int sum = 0;
printf("Type a String which will be converted to an Integer: ");
scanf("%s", input);
for (i = 0; i < strlen(input); i++)
{
if(input[i]>=48 && input[i]<=57)
{
//do something, it is a digit
printf("%d",input[i]-48);
//48 is ascii value of 0
}
}
Try it:
#include <stdio.h>
void main()
{
char input[100];
int i,j;
int val = 0;
printf("Type a String which will be converted to an Integer: ");
scanf("%s",input);
for(j=0; input[j] != '\0'; j++); // find string size
for (i = 0; i < j; i++)
{
val = val * 10 + input[i] - 48;
}
}
If you want your code to be portable to systems that don't use ASCII, you'll have to loop over your char array and compare each individual character in the source against each possible number character, like so:
int digit;
switch(arr[i]) {
case '0':
digit=0; break;
case '1':
digit=1; break;
// etc
default:
// error handling
}
Then, add the digit to your result variable (after multiplying it by 10).
If you can assume ASCII, you can replace the whole switch statement by this:
if(isdigit(arr[i])) {
digit=arr[i] - '0';
} else {
// error handling
}
This works because in the ASCII table, all digits are found in a single range, in ascending order. By subtracting the ordinal value of the zero character, you get the value of that digit. By adding the isdigit() macro, you additionally ensure that only digit characters are converted in this manner.
I am writing a basic C program which will take the input of a string, then convert it to an integer. I am aware of the standard atoi() function, this is purely an exercise I set myself. The code for the program is as follows:
#include <stdio.h>
#include <string.h>
int main (void) {
char input[20];
int counter, temp, magnitude = 0, value = 0;
scanf("%s", input); //takes user input for string to convert
for (counter = strlen(input); counter >= 0; counter--) { //from last to first char of input
temp = input[counter] - '0'; //converts from ASCII to actual value and stores in int
value += temp * magnitude * 10; //temp to correct magnitude and adds to total
magnitude++; //increments magnitude counter
}
printf("%d\n", value); //prints result
return 0;
}
I am trying to iterate backwards from the end of the string, then convert each character to it's actual value from ASCII, then convert it to the correct magnitude, before finally adding it to the final value. It is giving me values which are generally close although wrong.
For example 256 gives 220 and 90 gives 180.
You have two problems. Firstly, you're also trying to convert the terminating NUL byte, which doesn't make sense. Start iterating at strlen(input) - 1.
Second, for the magnitude you want to exponentiate, not multiply, i.e. 10, 100, 1000 rather than 10, 20, 30. For this, you can use pow(), for example:
for (counter = strlen(input) - 1; counter >= 0; counter--) { //from last to first char of input
temp = input[counter] - '0'; //converts from ASCII to actual value and stores in int
value += temp * pow(10, magnitude); //temp to correct magnitude and adds to total
magnitude++; //increments magnitude counter
}
counter = strlen(input)
should be
counter = strlen(input) - 1
so you're using the last valid character of the string.
Two problems here.
1) You should ignore the string null-terminator, so going from strlen(input)-1 will do
2) Your calculation is wrong. You should not multiply by magnitude, but raise 10 to it's power. Or simpler, it itself the required 10's power:
#include <stdio.h>
#include <string.h>
int main (void) {
char input[20];
int counter, temp, magnitude = 1, value = 0;
scanf("%s", input); //takes user input for string to convert
for (counter = strlen(input)-1; counter >= 0; counter--) { //from last to first char of input
temp = input[counter] - '0'; //converts from ASCII to actual value and stores in int
value += temp * magnitude ; //temp to correct magnitude and adds to total
magnitude*=10; //increments magnitude counter
}
printf("%d\n", value); //prints result
return 0;
}
strlen gives the total length of the string. So you have to use
counter = strlen(input)-1
In your for loop. This is because arrays in C start from 0 and end at strlen -1.
While your approach should work (after the issues noted in other answers have been fixed, anyway), it's probably simpler to take this approach:
value = 0;
for (char *p = input; *p; ++p)
value = value * 10 + (*p - '0');
That eliminates a couple unnecessary extra variables, and is probably a bit more efficient. It might not hurt to change the for loop termination condition to *p && isdigit(*p) - that would terminate the conversion on the first non-digit character seen, which might be a desirable approach for dealing with invalid input...
here is a complete answer,
that includes good programming paradigm practices
and defensive coding against user input problems
and results in the right answer
#include <stdio.h> // fgets(), exit(), printf()
#include <stdlib.h> // EXIT_FAILURE, perror()
#include <string.h> // strlen()
#include <ctype.h> // isdigit()
int main () // <-- do not use void
{
char input[20] = {'\0'};
int counter; // index into input array
int value = 0; // initialize the converted int from string
if( NULL != fgets(input, sizeof(input), stdin) )
{ // fgets failed
perror( "fgets failed for string input");
exit( EXIT_FAILURE );
}
// implied else, fgets successful
// note no need to replace trailing '\n' in following code block
for( counter=0; isdigit(input[counter]); counter++)
{
value = value*10 + (input[counter]-'0');
} // end for
printf("the converted value from %s is: %d\n", input, value); //prints result
return 0;
} // end function: main
These are the directions:
Read characters from standard input until EOF (the end-of-file mark) is read. Do not prompt the user to enter text - just read data as soon as the program starts.
Keep a running count of each different character encountered in the input, and keep count of the total number of characters input (excluding EOF).
I know I have to store the values in an array somehow using the malloc() function. I have to organize each character entered by keeping count of how many times that particular character was entered.
Thanks for the help!
Actually, since you are reading from standard input, there are at most 256 different possibilities. (You read in a char). Since that's the case, you could just statically allocate 256 integers for counting. int charCount[256]; Just initialize each value to 0, then increment each time a match is input.
Alternatively, if you must have malloc, then:
// This code isn't exactly what I'd turn in for homework - just a starting
// point, and non-tested besides.
int* charCount = (int*) malloc(sizeof(int) * 256); // Allocate 256.
for (int i = 0; i < 256; i++) charCount[i] = 0; // Initialize to 0.
// Counting and character input go here, in a loop.
int inputChar;
// Read in inputChar with a call to getChar(). Then:
charCount[inputChar]++; // Increment user's input value.
// Provide your output.
free(charCount); // Release your memory.
Here is a possible solution:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
int count[256] = {0};
char *l, *lp;
while (scanf(" %ms", &l) != EOF) {
for (lp = l; *lp; lp++)
count[(int)*lp]++;
free(l);
}
for (int i = 0; i < 256; i++) {
if (isprint(i) && count[i])
printf("%c: %d\n", i, count[i]);
}
exit(EXIT_SUCCESS);
}
Compile:
c99 t.c
Run:
$ ./a.out
abc
ijk
abc
<-- Ctrl-D (Unix-like) or Ctrl-Z (Windows) for EOF
a: 2
b: 2
c: 2
i: 1
j: 1
k: 1
I'm looking to read in a number from the keyboard and then I have to manipulate each digit individually (it's an Octal to Decimal converter).
Is there something similar to the charAt() method from Java that can be used to work with s particular digit?
I currently have the below code (incomplete) but when compiling, it returns "error: subscripted value is neither array nor pointer"
#include <stdio.h>
#include <math.h>
#include <string.h>
int main()
{
printf("Please enter an octal number ending with #");
char nextNum = getchar();
char number;
int counterUp = 0; //Records how many digits are entered
int counterDown = 1; //Records progress during conversion
int decimalNumber = 0;
while(nextNum != '#') //reads in the whole number, putting the characters together to form one Octal number.
{
number = (number + nextNum);
counterUp++;
nextNum = getchar();
}
//Begin converson from Octal to Decimal
while(counterUp >= 0)
{
int added = (number[counterUp] * (pow(8, counterDown)));
decimalNumber = (decimalNumber + added);
counterDown++;
}
}
I'm not looking to be told how to go from octal to decimal, just how to work with one digit at a time.
Use fgets() instead of a single char:
char number[25]; // max of 25 characters in string
fgets(number, 24, stdin); // read a line from 'stdin', with a max of 24 characters
number[24] = '\0'; // append the NUL character, so that we don't run into problems if we decide to print the string
Now you can subscript number at will, e.g. number[10] = 'A'.
I think you're used to Java way where you can write something like:
String number = "";
number += "3";
number += "4";
Strings in C do not work like that. This code doesn't do what you think it does:
char number = 0; // 'number' is just a one-byte number
number += '3'; // number now equals 51 (ASCII 3)
number += '4'; // number now equals 103 (meaningless)
Maybe something like this will work for you:
char number[20];
int i = 0;
number[i++] = '3';
number[i++] = '4';
Or, you could simply use scanf to read a number in from the keyboard.
I recommend that you find a good book about C and read about strings first, then scanf second.
I think you need to step back and look at your algorithm more closely.
What does char number store? What do you expect this loop to do:
while(nextNum != '#') //reads in the whole number, putting the characters together to form one Octal number.
{
number = (number + nextNum);
counterUp++;
nextNum = getchar();
}
In particular, what does number = (number + nextNum); mean?
You need to define number as an array of chars.
e.g.
char number[16];
Then change your reading loop to append to the array.
while(nextNum != '#')
{
number[counterUp] = nextNum;
counterUp++;
nextNum = getchar();
}