string in binary format to integer - c

i am trying to convert a string containing a 16-bit number in binary to a integer value.
It is a homework assignment and i have to use scanf("%1d.... ).
The problem i am having is that the loop wont end, i have no clue how to fix it.
for example:
input: 0000000000001111
output: 15
int read_binary_value()
{
int value = 0;
while( scanf("%1d", &value) == 1)
{
printf("%d ", value);
if (value == 1)
{
value += 1;
value << 1;
}
}
printf("yoyoyoyoyoyoyo");
printf("%d",value);
return value;
}

I modified your code and it works
int read_binary_value()
{
int total=0;
int value;
while( scanf("%1d", &value) == 1)
{
printf("%d", value);
if(!(value==0||value==1))
{
//Generate Error Message and Exit program
}
total = total << 1;
if (value == 1)
{
total += 1;
}
}
printf("yoyoyoyoyoyoyo\n");
printf("%d",total);
return total;
}
Your loop stop when get end of file.
Press CTRL+Z for windows and Ctrl+D for linux. Those are End of File character.

If you want to get 16 inputs you can use
for(i=0;i<16;i++) instead of the while to just run the loop 16 times and end. Or else within the while loop you can give
if(i==16)
break; incrementing i at the end of the loop. If you need to manually stop the loop, EOF char is the option.

Related

Counting the number of zero in an integer

The program would ask the user an integer input.
and it counts how many zero the int has.
constraints: use while loop
ex:
input: 2400
count: 2
now I have no problem in that part, only when the user would input a zero.
supposed it counts 1.
ex:
input 0
count: 1
but then the program returns count 0.
here's the code:
int main(){
int n, counter = 0;
printf("Enter the number: ");
scanf("%d", &n);
while(n != 0){
if(n % 10 == 0){
counter ++;
n=n/10;
}else{
break;
}
}
printf("%d", counter);
return 0;
}
Use functions.
int countZeroes(int x)
{
int result = !x; // if x == 0 then result = 1
while(x)
{
result += !(x % 10);
x /= 10;
}
return result;
}
int main(void)
{
printf("%d\n", countZeroes(0));
printf("%d\n", countZeroes(1000));
printf("%d\n", countZeroes(-202020));
}
https://godbolt.org/z/91hKr46eo
You have while(n != 0) this does so when you enter just 0 it doesn't run. So the counter that you have set to 0 at the beginning is still 0
Here is what I would have done :
int main()
{
int num, count = 0;
scanf("%d",&num);
if (num == 0) {
printf("1");
return 0;
}
while(num != 0) //do till num greater than 0
{
int mod = num % 10; //split last digit from number
num = num / 10; //divide num by 10. num /= 10 also a valid one
if(mod == 0) count ++;
}
printf("%d\n",count);
return 0;
}
Just don't forget to consider everything that can happen with a condition that you set
**Fixed it
A different version that prints the integer as a string, and looks for '0' characters in it. Tested.
#include <stdio.h>
#include <string.h>
int main(void)
{
int input = 0;
int zeroes = 0;
char *foundpos, teststring[100];
scanf("%d", &input);
sprintf(teststring, "%d", input);
foundpos = strchr(teststring, '0');
while (foundpos != NULL) {
++zeroes;
foundpos = strchr(foundpos + 1, '0');
}
printf("%d contains %d zeroes", input, zeroes);
}
Just count the zero digits you get between \n chars.
#include <stdio.h>
int main()
{
int ndigs = 0, c;
while ((c = getchar()) != EOF) {
switch (c) {
case '0': ndigs++;
break;
case '\n': printf(" => %d zero digs", ndigs);
ndigs = 0;
break;
}
putchar(c);
}
}
sample output:
$ ./a.out
123001202010
123001202010 => 5 zero digs
^D
$ _
No need to convert digits to a number, to convert it back to decimal digits. You can improve the program counting digits until a nondigit is detected, then output. But there's no need to convert a decimal representation of a number (in base 10) to internal representation to then get the digits you have destroyed (in the conversion) back again to count them.
As earlier mentioned, the problem is with the loop:
while(n != 0){
if(n % 10 == 0){
counter ++;
n=n/10;
}else{
break;
}
}
It doesnt do anything in case n == 0. But replacing it with n > 0 is not a good solution because ints can be negative too.
You should use do{}while() construction instead, it will always do one iteration of loop no matter what condition you put there. Notice that no matter what you get as a number, it is still a number so you can do one iteration of loop either way.
Just do as follows:
do{
if(n % 10 == 0){
counter ++;
n=n/10;
}else{
break;
}
} while( n != 0 );
This should work(if i didnt mess up the braces/semicolumns).

After inputting an integer for a scanf() function, code does not continue?

My objective is to create a program that checks if a specific bit (entered by the user) is set in a hard-coded integer (in this case 159). This code compiles, however when I enter my desired integer, the console stalls for about a second and then exits the program with no error message. None of the printf() functions are executed, as nothing else is printed out on the console before it exits. I'm fairly new to C, so I need some help with this.
#include <stdio.h>
int main() {
int x = 159;
int position = 1;
scanf("%d", position);
if (position == 0) {
position = 1;
printf("if");
}
else {
for (int i = 0; i < position; i++) {
position *= 2;
}
printf("else");
}
printf("%d", position);
if ((x & position) != 0) {
printf("true");
}
else {
printf("false");
}
}
scanf function takes address of variable like this scanf("%d", &position);
not variable itself.
it will place entered value in that address so you need to add & to your scanf.
and even after that. except when your position is 0 this code will never work:
else {
for (int i = 0; i < position; i++) {
position *= 2;
}
printf("else");
}
this is an infinitive loop.It will execute until position become so large that int doesn't have enough space to store it so position become some illogical number like uninitialized variables.

How to make an array accept only numbers in c programming?

So my task is to make an array that accepts 10 characters. If the characters entered by the user are greater than 10, then an error is dispayed. If the 10 characters entered contain a letter, it displays another error.
Therefore, the array can only have 10 numbers and nothing else, if the numbers entered are less or more than 10, error is displayed as well as if there are letters in the array.
My code accepts both numbers and letters, as i cannot figure out how to display error when letters are entered.
void getTenDigitPhone(char telNum[])
{
int i;
int z = 1;
do
{
scanf("%s", telNum);
if (strlen(telNum) != 10)
{
printf("Enter a 10-digit phone number: ");
z = 1;
}
else if (strlen(telNum) == 10)
{
return telNum;
}
} while (z == 1);
}
You just need to check that telNum contains only digits:
for (int i = 0; i < 10; i++)
if (!isdigit(telNum[i])) {
// handle error because a non-digit was found.
}
I'm not going to do your homework for you but this should give you the idea.
You can use the function isdigit(x).
This returns true (non-zero) if x is a digit and returns false (zero) if not.
You have to check digit by digit.
I'm going to give an answer because you have posted your current code as your effort. As other answers you should use isdigit(x) function.
...
else if (strlen(telNum) == 10)
{
int i;
char err = 0;
for (i = 0; i < 10; i++) {
if (!isdigit(telNum[i])) {
// Your error here
printf("Non-digit character found");
err = 1;
break;
}
}
if (err == 0) {
return telNum;
}
}
...

how to get program to accept only positive integer values in c

writing a program that will be finding min, max, avg of values entered by user. Having trouble writing something that will check to make sure there are only postive integers entered and produce an error message. heres my for statement that is reading the input so far:
for (int value = 0; value <= numofvals; ++value) {
printf("Value %d: %f\n", value, val_input);
scanf("%f", &val_input);
}
mind you I've been learning code for about 3 weeks and was just introduced to loops this week so my understanding is rudimentary at best!
First, don't use scanf. If stdin doesn't match what it expects it will leave it in the buffer and just keep rereading the same wrong input. It's very frustrating to debug.
const int max_values = 10;
for (int i = 0; i <= max_values; i++) {
int value;
if( scanf("%d", &value) == 1 ) {
printf("Got %d\n", value);
}
else {
fprintf(stderr, "I don't recognize that as a number.\n");
}
}
Watch what happens when you feed it something that isn't a number. It just keeps trying to read the bad line over and over again.
$ ./test
1
Got 1
2
Got 2
3
Got 3
foo
I don't recognize that as a number.
I don't recognize that as a number.
I don't recognize that as a number.
I don't recognize that as a number.
I don't recognize that as a number.
I don't recognize that as a number.
I don't recognize that as a number.
I don't recognize that as a number.
Instead, use fgets to reliably read the whole line and sscanf to parse it. %f is for floats, decimal numbers. Use %d to recognize only integers. Then check if it's positive.
#include <stdio.h>
int main() {
const size_t max_values = 10;
int values[max_values];
char buf[1024];
size_t i = 0;
while(
// Keep reading until we have enough values.
(i < max_values) &&
// Read the line, but stop if there's no more input.
(fgets(buf, sizeof(buf), stdin) != NULL)
) {
int value;
// Parse the line as an integer.
// If it doesn't parse, tell the user and skip to the next line.
if( sscanf(buf, "%d", &value) != 1 ) {
fprintf(stderr, "I don't recognize that as a number.\n");
continue;
}
// Check if it's a positive integer.
// If it isn't, tell the user and skip to the next line.
if( value < 0 ) {
fprintf(stderr, "Only positive integers, please.\n");
continue;
}
// We got this far, it must be a positive integer!
// Assign it and increment our position in the array.
values[i] = value;
i++;
}
// Print the array.
for( i = 0; i < max_values; i++ ) {
printf("%d\n", values[i]);
}
}
Note that because the user might input bad values we can't use a simple for loop. Instead we loop until either we've read enough valid values, or there's no more input.
Something easy like this may work for you:
int n;
int ret;
for (;;) {
ret = scanf("%d", &n);
if (ret == EOF)
break;
if (ret != 1) {
puts("Not an integer");
for (;;)
if (getchar() == '\n')
break;
continue;
}
if (n < 0) {
puts("Not a positive integer");
continue;
}
printf("Correct value %d\n", n);
/* Do your min/max/avg calculation */
}
/* Print your results here */
This is just an example and assumes you do not need to read floating point numbers and then check if they are integers, as well as a few other things. But for starters, it is simple and you can work on top of it.
To break out of the loop, you need to pass EOF (typically Ctrl+D in Linux/macOS terminals, Ctrl+Z in Windows ones).
An easy and portable solution
#include <limits.h>
#include <stdio.h>
int get_positive_number() {
char buff[1024];
int value, ch;
while (1) {
printf("Enter positive number: ");
if (fgets(buff, 1023, stdin) == NULL) {
printf("Incorrect Input\n");
// Portable way to empty input buffer
while ((ch = getchar()) != '\n' && ch != EOF)
;
continue;
}
if (sscanf(buff, "%d", &value) != 1 || value < 0) {
printf("Please enter a valid input\n");
} else {
break;
}
}
return value;
}
void solution() {
// Handling malformed input
// Memory Efficient (without using array to store values)
int n;
int min = INT_MAX;
int max = INT_MIN;
double avg = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
getc(stdin);
int value;
for (int i = 0; i < n; i++) {
value = get_positive_number();
if (value > 0) {
if (min > value) {
min = value;
}
if (max < value) {
max = value;
}
avg += value;
}
}
avg = avg / n;
printf("Min = %d\nMax = %d\nAverage = %lf\n", min, max, avg);
}
int main() {
solution();
return 0;
}
Output:
Enter number of elements: 3
Enter positive number: 1
Enter positive number: 2
Enter positive number: a
Please enter a valid input
Enter positive number: -1
Please enter a valid input
Enter positive number: 1
Min = 1
Max = 2
Average = 1.333333

How do you print different things depending the user input?

First, I apologize if the question doesn't make sense as my English isn't that good...
My question is, how do we print out different things depending on the user input?
What I'm trying to do is: when user inputs integer, the program prints out the inputted number. When the user inputs something that's not integer (like symbols and characters), the program prints out "not integer".
my current idea (pseudo-code) is as follows:
`int main(){
int value;
printf("Enter numbers");
scanf("%d", &value);
if(value is integer){
printf("%d", value);
} else {
printf("not integer");
}
return 0;
}`
what gets me is the scanf; by using %d, I'm assuming that the user will input an integer values, but the user can input values that are not integers so I can't make a comparison using the if statement if( value is integer). How can I make a comparison that will determine whether the inputted value is integer or not?
I don't know if this is a good thing or not.
You can use ASCII to check if the input type is an integer or not
(between 48 - 57 in ASCII)
it will be like this
char value;
int flag = 0; //to check true or false (0 means false, and 1 means true)
printf("Enter numbers");
scanf("%c", &value);
for(int i = 48; i <= 57; i++){
if(value == i){
flag = 1;
break;
}
}
if(flag == 1){
printf("%c", value);
} else {
printf("not integer");
}
How do you print different things depending the user input?
Step 1: Read the line of user input
char buf[100];
if (fget(buf, sizeof buf, stdin)) {
// something was entered
Step 2: test the string
char *end;
long value = strtol(buf, *end);
// If the end is the same as the beginning, no conversion occurred.
if (end == buf) {
puts("not integer");
}
printf("%ld\n", value);
}
}
Additional code could look for input that occurred after the integer. Also code could test for a large number that overflowed the long range.
The code is as follows. It caters for different situations like inputting negative numbers and decimal numbers:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char input[20];
int wrongFlag = 0;
scanf("%s", input);
if (input[0] == '0' && strlen(input) > 1) {
wrongFlag = 1;
//for number starts with 0, and string length>1 eg: 010
}
for (int i = 0; i < strlen(input); i++) {
if (i == 0 && (input[i] == '-' && strlen(input) > 2 && input[i + 1] == '0')) {
//check first round only: negative number with length >2 and starts with 0 eg: -010.
wrongFlag = 1;
continue;
}
if (i != 0 && !isdigit(input[i])) {
//check following rounds, check if it is not digit
wrongFlag = 1;
break;
}
}
if (wrongFlag) {
printf("Not integer");
}
else {
printf("integer");
}
return 0;
}
Try this it works for me.
#include<stdio.h>
#include<string.h>
int main()
{
int i;
char value[50];
int len;
printf("Enter maximum 50 digits\n");
/* enter the values you wanted*/
printf("Enter the value: ");
gets(value);
len = strlen(value);
/*it will iterate upto the end of the user input*/
for(i=0;i<len;i++)
{
if(48<value[i] && value[i]<=57)
{
if(i==(len-1))
printf("It's an integer");
}
else{
printf(" Not an integer");
break;
}
}
return 0;
}

Resources