Why this function is giving unexpected result? - c

I was trying to co
So, I don't understand the reason why my compiler is not letting me take input when the convhex() is called from the main. It's directly printing some result.. I don't understand this.
Here's the code..
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <String.h>
void convhex();
void convert(int no, int base);
int checkValid(int base,int no);
// function prototyping done here
void convhex()
{
char ch[10];
int dec=0;
int i, res;
printf("Enter the hexadecimal number \n");
scanf("%[^\n]", ch);
// print in decimal
for(i=strlen(ch)-1;i>=0;i--)
{
if(ch[i]>65)
res=ch[i]-65+10;
else
res=ch[i]-48;
//printf("%d", res);
dec=dec+pow(16,strlen(ch)-(i+1))*res;
}
printf("\nThe number in decimal is %d \n", dec);
}
int checkValid(int base,int no)
{
int rem;
//flag;
// flag=0;
while(no>0)
{
rem=no%10;
if(rem>base)
{
//flag=1;
//break;
return 0;
}
no/=10;
}
return 1;
/*
if(flag==1)
printf("Invalid Input");
else
printf("Valid Input");
*/
}
void convert(int no, int base)
{
int temp, mod, sum=0, i=0;
temp=no;
while(temp>0)
{
mod=temp%10;
temp=temp/10;
sum=sum+pow(base,i)*mod;
i++;
}
printf("\n The number in base 10 is %d", sum);
}
int main()
{
int base, no;
printf("Enter the base \n");
scanf("%d", &base);
if(base==16)
convhex();
else
{
printf("Enter the number \n");
scanf("%d", &no);
printf("You have entered %d", no);
if(checkValid(base, no))
convert(no, base);
}
return 0;
}
// up until now our program can work with any base from 0-10 but not hexadecimal
// in case of hex, we have A-F

scanf in convhex is reading the \n left by the scanf in main.
Try this
scanf(" %[^\n]", ch);
^ An extra space will eat any number of white-spaces.

you can just remove the %[^\n] from scanf in connhex to change it to:
scanf("%s", ch)
or you could do what haccks suggested in the above post.

Related

I want to make an error information when user type the wrong factors

I want to create a debug system in this code.
For example: I want to show the error information when user enters the wrong factors.
I can't figure out a method. If you still don't get it, you can take a look at this photo.
And this is my guessing game code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void guessing();
int main()
{
char option;
do{
guessing();
printf("Do you want to continue(y/n): \n");
scanf(" %c", &option);
}while(option=='y'); //when while set up,carry out "do".
return 0;
}
void guessing(){ //guessing function
srand(time(0)); //different number to make.
int answer = rand() % 100; //range at 0~99
int guess;
do
{
printf("pls enter your number to guess(0~99): ");
scanf("%d", &guess);
if (guess > answer)
{
printf("smaller.\n");
}
else if (guess < answer)
{
printf("bigger\n");
}
else if (guess == answer)
{
printf("got it! The answer is %d\n", answer);
}
}while (guess != answer);
return;
}
Read input as String and if it was number, do your operations.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
void guessing();
int main()
{
char option;
do{
guessing();
printf("Do you want to continue(y/n): \n");
scanf(" %c", &option);
}while(option=='y'); //when while set up,carry out "do".
return 0;
}
void guessing(){ //guessing function
srand(time(0)); //different number to make.
int answer = rand() % 100; //range at 0~99
int guess;
char in[32] = {0};
int i=0;
char isNumber = 0;
do
{
isNumber = 1;
printf("pls enter your number to guess(0~99): ");
scanf("%s", in);
for(i=0;i<strlen(in);i++) {
if(!isdigit(in[i])) {
printf("Error in input\n");
isNumber = 0;
break;
}
}
if(!isNumber)
continue;
guess = atoi(in);
if (guess > answer)
{
printf("smaller.\n");
}
else if (guess < answer)
{
printf("bigger\n");
}
else if (guess == answer)
{
printf("got it! The answer is %d\n", answer);
}
}while (guess != answer);
return;
}

In decision if else, Whenever i put the correct int number instead of printing Correct its Print Invalid

Whenever i put the correct int number instead of printing Correct its Print Invalid.
int main(void)
{
int number = 042646;
int pass;
printf("Enter the PIN.\n");
scanf("%d", &pass);/*enter code here*/
if (pass == number)
{
printf("Correct\n");
}
else
{
printf("Invalid\n");
}
}
In "C" a number preceded by 0 is interpreted as an octal number. Here is a simple code which will help you to see the issue:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int number = 42646;
int number_octal = 042646;
int pass = 0;
printf("Enter the PIN.\n");
scanf("%d", &pass);/*enter code here*/
/* Debug */
printf("Pass: %d\n", pass);
printf("Number: %d\n", number);
printf("number_octal: %d\n", number_octal);
if (pass == number)
{
printf("Correct\n");
}
else
{
printf("Invalid\n");
}
return 0;
}

Program is terminating without recognizing scanf

I don't know why my program terminates before confirmStats(); is called. I included everything related in main() in case the issue is ocurring somewhere else in my program.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int str, intel, charis;
int totalPts =5;
/* Returns a number.
User must input an integer.
*/
int getNumber(int number){
while(scanf("%d", &number) != 1){
printf("You did not enter a valid number\n");
scanf("%*s");
}
return number;
}
/* Individual stat points */
int stat(int number){
number = getNumber(number);
while(number > totalPts){
printf("You only have %d stat points left\n", totalPts);
printf("Enter a number less than or equal to %d:\t", totalPts);
number = getNumber(number);
}
totalPts -= number;
printf("Points remaining:\t%d\n", totalPts);
return number;
}
/* Player stat points */
void getStats(){
printf("You're alotted %d stat points to spend in Strength, Intellect, and Charisma\n", totalPts);
printf("Intellect:\t");
intel = stat(intel);
printf("Strength:\t");
str = stat(str);
printf("Charisma:\t");
charis = stat(charis);
printf("\nIntellect: %d\t Strength: %d\t Charisma: %d\n", intel, str, charis);
}
void confirmStats(){
char ans;
scanf("%c", &ans);
while(ans == 'n'){
str = 0;
intel = 0;
charis = 0;
getStats();
printf("Are these correct?:\ty/n: ");
scanf("%c", &ans);
}
}
void main(){
printf("\nSafe choice...");
printf("\n");
printf("Alright, how old are you?\n");
// int age, str, intel, charis;
int age;
// int totalPts = 5;
age = getNumber(age);
getStats();
printf("Are these correct? ");
printf("\n");
printf("y/n:\t");
printf("\n");
confirmStats();
}
The problem is that scanf("%c", &ans); scans the newline character left over by the previous scanf.
The fix is easy. Simply add a space before %c in the two scanfs in confirmStats. The space is a whitespace character and a whitespace character in the format string of scanf tells scanf to scan any number of whitespace characters, if any, until the first non-whitespace character.
Improved code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int str, intel, charis;
int totalPts = 5;
/*
Returns a number.
User must input an integer.
*/
int getNumber(){
int number;
while(scanf("%d", &number) != 1){
printf("You did not enter a valid number\n");
scanf("%*s");
}
return number;
}
/* Individual stat points */
int stat(){
int number;
number = getNumber();
while(number > totalPts){
printf("You only have %d stat points left\n", totalPts);
printf("Enter a number less than or equal to %d:\t", totalPts);
number = getNumber();
}
totalPts -= number;
printf("Points remaining:\t%d\n", totalPts);
return number;
}
/* Player stat points */
void getStats(){
printf("You're alotted %d stat points to spend in Strength, Intellect, and Charisma\n", totalPts);
printf("Intellect:\t");
intel = stat();
printf("Strength:\t");
str = stat();
printf("Charisma:\t");
charis = stat();
printf("\nIntellect: %d\t Strength: %d\t Charisma: %d\n", intel, str, charis);
}
void confirmStats(){
char ans;
scanf(" %c", &ans);
while(ans == 'n'){
str = 0;
intel = 0;
charis = 0;
getStats();
printf("Are these correct?:\ty/n: ");
scanf(" %c", &ans);
}
}
int main(void){
printf("\nSafe choice...");
printf("\n");
printf("Alright, how old are you?\n");
age = getNumber();
getStats();
printf("Are these correct? ");
printf("\n");
printf("y/n:\t");
printf("\n");
confirmStats();
return 0;
}
int getNumber(int number){
int ok = 0;
while (!ok){
if(scanf("%d", &number) != 1){
printf("You did not enter a valid number\n");
while(getchar()!='\n');
}
else {
getchar();
ok=1;
}
}
return number;
}
Sir ,do u have checked the syntax is scant("%d",&variable);
Not. scant("%d",variable);

My string compare is coming out wrong

hi my program is to enter a number which gives the length of the string then the string and then finally a letter which should then tell me how many times that letter is in the string. Currently to help me figure out what is wrong with my code i can see that the strcmp is resulting in the same ascii number but negative. eg for the letter a the number is 97 but the strcmp is giving out -97 so the strcmo doesnt show the character as being in the string and results in the incorrect result. Any help would be greatly appreciated. thanks
#include
#include
int main(void)
{
char myChar[100], z, k;
int counter, n, g=0, r, i, l;
counter=0;
scanf("%d",&n);
while (counter<n)
{
counter++;
scanf(" %c",&myChar[counter]);
}
scanf(" %s", &z);
for(i=0;i<n+1;++i)
{
k=myChar[i];
r=strcmp(&z, &k);
l=r;
//printf("\n%c", myChar[i]);
printf("%d\n", l);
if(r==0)
{
g++;
printf("%d\n", g);
}
}
printf("\n\n%d\n", g);
return (0);
}
#include <stdio.h>
#include <string.h>
int main(void){
char myChar[100], str[64];//
int counter, n;
int i, j, k;
printf("number of charactors : ");
scanf("%d",&n);
for (i=0; i<n; ++i){
scanf(" %c", &myChar[i]);
}
printf("input string : ");
scanf("%63s", str);//"%s" : The useless one letter to input as a string. "%c" for &z
for(i=0;i<n;++i){
counter = 0;
for(j=0;str[j]!='\0'; ++j){
k = (str[j] == myChar[i]);//Comparison of each character
counter += k;//if(str[j] == myChar[i]) ++counter;
}
printf("%c is %d\n", myChar[i], counter);
}
return (0);
}

How to use a loop function with user input in C?

Here is the average program I created.
#include <stdio.h>
#include <stdlib.h>
int main()
{
float f1,f2,f3;
/* Program to calculate averages. */
/*Asks for the numbers.*/
printf(" Please enter three numbers.\n");
printf ("\t" "First number please.\n");
scanf("%f", &f1);
printf ("\t" "Second number please.\n");
scanf ("%f", &f2);
printf("\t" "Third number please.\n");
scanf("%f", &f3);
/* Now it averages it.*/
printf(" Thank you, wait one.\n");
printf(" Excellent, your sum is.\n");
printf("%f""\n", f1+f2+f3);
printf("Your average of the sum is now!!!!\n");
printf("%f", (f1+f2+f3)/3);
return 0;
}
Now would I turn this into a do-while? Or an if else?
If you want to repeat the whole entry and averaging process, you can wrap a loop around the code:
#include <stdio.h>
int main(void)
{
float f1,f2,f3;
while (1)
{
printf("Please enter three numbers.\n");
printf("\tFirst number please.\n");
if (scanf("%f", &f1) != 1)
break;
printf("\tSecond number please.\n");
if (scanf("%f", &f2) != 1)
break;
printf("\tThird number please.\n");
if (scanf("%f", &f3) != 1)
break;
printf("Your sum is %f\n", f1+f2+f3);
printf("Your average is %f\n", (f1+f2+f3)/3);
}
return 0;
}
Note that this code checks the return value from scanf() each time it is used, breaking the loop if there's a problem. There's no need for string concatenation, and a single printf() can certainly print a string and a value.
That's a simple first stage; there are more elaborate techniques that could be used. For example, you could create a function to prompt for and read the number:
#include <stdio.h>
static int prompt_and_read(const char *prompt, float *value)
{
printf("%s", prompt);
if (scanf("%f", value) != 1)
return -1;
return 0;
}
int main(void)
{
float f1,f2,f3;
while (printf("Please enter three numbers.\n") > 0 &&
prompt_and_read("\tFirst number please.\n", &f1) == 0 &&
prompt_and_read("\tSecond number please.\n", &f2) == 0 &&
prompt_and_read("\tThird number please.\n", &f3) == 0)
{
printf("Your sum is %f\n", f1+f2+f3);
printf("Your average is %f\n", (f1+f2+f3)/3);
}
return 0;
}
If you want to get away from a fixed set of three values, then you can iterate until you encounter EOF or an error:
#include <stdio.h>
static int prompt_and_read(const char *prompt, float *value)
{
printf("%s", prompt);
if (scanf("%f", value) != 1)
return -1;
return 0;
}
int main(void)
{
float value;
float sum = 0.0;
int num = 0;
printf("Please enter numbers.\n");
while (prompt_and_read("\tNext number please.\n", &value) == 0)
{
sum += value;
num++;
}
if (num > 0)
{
printf("You entered %d numbers\n", num);
printf("Your sum is %f\n", sum);
printf("Your average is %f\n", sum / num);
}
return 0;
}
You might also decide to replace the newline at the ends of the prompt strings with a space so that the value is typed on the same line as the prompt.
If you want to check whether to repeat the calculation, you can use a minor variant on the first or second versions of the code:
#include <stdio.h>
static int prompt_and_read(const char *prompt, float *value)
{
printf("%s", prompt);
if (scanf("%f", value) != 1)
return -1;
return 0;
}
static int prompt_continue(const char *prompt)
{
printf("%s", prompt);
char answer[2];
if (scanf("%1s", answer) != 1)
return 0;
if (answer[0] == 'y' || answer[0] == 'Y')
{
int c;
while ((c = getchar()) != EOF && c != '\n') // Gobble to newline
;
return 1;
}
return 0;
}
int main(void)
{
float f1,f2,f3;
while (printf("Please enter three numbers.\n") > 0 &&
prompt_and_read("\tFirst number please.\n", &f1) == 0 &&
prompt_and_read("\tSecond number please.\n", &f2) == 0 &&
prompt_and_read("\tThird number please.\n", &f3) == 0)
{
printf("Your sum is %f\n", f1+f2+f3);
printf("Your average is %f\n", (f1+f2+f3)/3);
if (prompt_continue("Do you want to try again?") == 0)
break;
}
return 0;
}
You can do this:
int main()
{
float number, sum=0.0f;
int index=0;
do
{
printf ("\t" "Enter number please.\n"); //Asking for a number from user
scanf("%f", &number); //Getting a number from a user
sum+=number; //Add number entered to the sum
i++;
} while (i < 3);
printf("Excellent, your average is %f\n", sum/3);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
float f1,f2,f3;
char c='Y';
/* Program to calculate averages. */
/*Asks for the numbers.*/
do
{
printf(" Please enter three numbers.\n");
printf ("\t" "First number please.\n");
scanf("%f", &f1);
printf ("\t" "Second number please.\n");
scanf ("%f", &f2);
printf("\t" "Third number please.\n");
scanf("%f", &f3);
/* Now it averages it.*/
printf(" Thank you, wait one.\n");
printf(" Excellent, your sum is.\n");
printf("%f""\n", f1+f2+f3);
printf("Your average of the sum is now!!!!\n");
printf("%f", (f1+f2+f3)/3);
printf ("Do you wana continue [Y/N]...\n");
scanf("%c", &c);
}while(c!='N'&&c!='n');
return 0;
}

Resources