Why won't my program print out a character in c? - c

Why won't my program print out a character in c? I can not seem to find any error in this. Below is a snippet of my program. When I tried to print firstBand character out, all i get is nothing.
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
int bandOne;
int bandTwo;
double multiplierValue;
double resistanceValue;
double toleranceValue;
char firstBand;
char secondBand;
char multiplier;
char tolerance;
int main(void) {
//prompt user for band colours
printf("Colour of first band?\n");
firstBand = scanf(" %c",&firstBand);
printf("Colour of second band?\n");
secondBand = scanf(" %c",&secondBand);
printf("What is multiplier?\n");
multiplier = scanf(" %c",&multiplier);
printf("What is the tolerance?\n");
tolerance = scanf(" %c",&tolerance);
printf("%c\n",firstBand);
....
..
..
return 0;
}
please help.

firstBand = scanf(" %c",&firstBand);
firstband is a character read and scanf() returns number of elements successfully read.
So firstBand is no more a char which you have scanned and it is actually the value of number of elements read.
if(scanf(" %c",&firstBand) == 1)
printf("%c",firstBand);

Change all of your scanf statements from
firstBand = scanf(" %c",&firstBand);
to
scanf(" %c",&firstBand);
That should fix it.

Related

Variable Use Fgets with a char array in C

I'm trying to read in a grade (1-10) into an array called moduleGrades.
The fgets(moduleGrades[i]-1, sizeof(moduleGrades), stdin); causes an error, yet what i've typed is exactly what I need. I want to store 3 grades (if the number of modules entered was 3)
many thanks.
#include<stdio.h>
#include <string.h>
char name[30];
int moduleNumber;
char moduleGrades[2];
int main(int argc, char **argv)
{ //read name & module amount
printf ("Please enter your name: ");
fgets(name, sizeof(name), stdin);
printf ("How many Modules: ");
scanf("%d", &moduleNumber);
int i;
for (i = 1; i <= moduleNumber; i++)
{
printf ("Please enter module %d grade ", i);
fgets(moduleGrades[i]-1, sizeof(moduleGrades), stdin);
}
printf("%d", moduleGrades[0]);
printf("%d", moduleGrades[1]);
printf("%d", moduleGrades[2]);
return 0;
}
If you want to print three chars, as indicated by your output, then your array must also be able to hold three chars:
char moduleGrades[2];
Also this loop here:
int i;
for (i = 1; i <= moduleNumber; i++)
This isn't wrong in itself because you subtract the 1 you're off inside the loop, but I would do this and just put this instead:
for (int i = 0; i < moduleNumber; i++)
The fgets call inside the loop is wrong. You're giving it a char instead of a pointer to char. Instead of using fgets, I would just use scanf again:
scanf(" %c", &moduleGrades[i]);
When you print those char that you read in, you need to use the %c format specifier, too:
printf("%c", moduleGrades[0]);
This way it'll print the char that you read in earlier. For instance, if you pressed A, it will print A. With %d it will probably print 65, but it's undefined behavior, so anything else than that might happen instead and there's no guarantee on what exactly will happen.

How to make code say 'invalid input' when a user enters a character or a string (Validate)

I'm new to c and i just wanted to know how to make my code say ' invalid input' if they decide to enter a character or gibberish.
My code is just a simple Celsius to Kelvin (i know very simple) and i just adds 273 to any inputted number. i tried to use isdidgit but it was unsuccessful.
My code;
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int temp = 273;
int cel;
int cel2;
int choice;
switch (choice)
{
case 1:
printf("enter ce to conv to kel: ");
scanf("%ld", &cel);
cel2 = cel + temp;
printf("%d in Celsuis is: %d Kelvin \n", cel, cel2)
I accept all feedback / improvements,
thanks
~Neamus
Presently, your code has no way to recover from an invalid input. That is, if a user enters "a" when prompted, scanf() will never return because it will be waiting for a base-10 integer value.
What you will need to do is read the input as a C-string and process that:
char input[80];
do {
printf("enter ce to conv to kel: ");
scanf("%79[^\n]\n", input); // read until newline; toss newline
} while (input_is_bad(input)); // your function to validate input
cel = atoi(input); // atoi parses C-string, returning an int
cel2 = cel + temp;
printf("%d in Celsuis is: %d Kelvin \n", cel, cel2);
Inside your own input_is_bad() function, you can print a message stating that the input is not valid.
You can achieve this by using fgets and strtol. See the following code:
#include<stdio.h>
#include <stdlib.h>
int main()
{
int temp = 273;
int cel;
int cel2;
int choice;
int flag;
char *p, str[100];
printf("enter ce to conv to kel: ");
while (fgets(str, sizeof(str), stdin)) {
cel = strtol(str, &p, 10); //number of base 10
if (p == str || *p != '\n') {
printf("Please enter an integer: ");
}
else break; //if input is integer then break the loop
}
//do your calculations here
return 0;
}

Scanning a char array after scanning an integer in C

I'm a newbie in programming. It is confusing me when I taking input of a char array after scanning an integer. It is not working properly.
The code is following:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[30];
int x,y;
scanf("%d",&x);
scanf("%[^\n]",a);
scanf("%d",&y);
printf("%d\n%s\n%d",x,a,y);
return 0;
}
Output is following:
The problem is due to the white spaces.After scanf("%d",&x); the last entered '\n' character is taken and saved the string a of scanf("%[^\n]",a).
To avoid this give space in scanf() statement
scanf(" %[^\n]",a);//give a space
Why to give a space?
By giving a space,the compiler consumes the '\n' character or any
other white space ('\0','\t' or ' ' ) from the previous scanf()
your code :
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[30];
int x,y;
scanf("%d",&x);
scanf(" %[^\n]",a);//give a space
scanf("%d",&y);
printf("%d\n%s\n%d",x,a,y);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[30];
int x,y;
scanf("%d",&x);
fflush(stdin);
scanf("%[^\n]",a);
fflush(stdin);
scanf("%d",&y);
printf("%d\n%s\n%d",x,a,y);
return 0;
}
This also works. The same goes here, /0 at the end adds up to the character scan and interferes. Using fflush(stdin) will discard any unnecessary input data including the /0.
Correct me if I am wrong as I too am a newbie at coding. :p
Replace scanf("%[^\n]",a); with scanf(" %99[^\n]", a);
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[30];
int x,y;
scanf("%d",&x);
scanf("%s",a); // get char array without inputing space
scanf(" %99[^\n]", a); // get char array, allowing inputing space
scanf("%d",&y);
printf("%d\n%s\n%d\n",x,a,y);
return 0;
}
Instead of %d use %d\n to consume the newline, so that the following command will not just read nothing:
scanf("%d\n",&x);
scanf("%[^\n]",a);
scanf("%d",&y);
printf("%d\n%s\n%d",x,a,y);

how to display entered letter in c?

I am new to c programming. I have created a program for entered letters and finally displayed the entered letters.. but it displayed only final letters always.. please help .. i know its simple question but am beginner so please help guys..
#include<stdio.h>
int main()
{
char z;
int a;
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%s",&z);
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%s\n",&z);
}
return 0;
}
Problems:
You should use %c (for character) instead of %s (for string).
Use a character array for storing multiple characters. Read about arrays here.
Remove & from printf() in the second for loop.
Try this:
int main()
{
char z[10]; //can hold 10 characters like z[0],z[1],z[2],..
int a;
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",&z[i]);
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%c\n",z[i]);
}
return 0;
}
Please look into this for more details on scanf. You have given scanf("%s",&z); %s is for reading strings(array of chars except newline char and ended with null char). So if you put this inside loop you wont get desired result. And if you want read only a char at a time use %c here c for Character.
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",z+i);
}
char z is a place holder for one character only. And you are over writing what you set z to in the for loop. To take in more characters, use a char array as others have mentioned.
Or print the characters in the same you loop you are scanning them:
#include<stdio.h>
int main()
{
char z;
int a;
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%s",&z);
printf("letter scanned:%c\n", z);
}
return 0;
}
Letters are scanned using %c. And to scan multiple letters you can use char array: char z[10];
What you are trying to do can be done this way:
char z[10]; // Take some max size array
...
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",&z[i]); // Scan the letters on each array position.
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%c\n",z[i]); //'printf' doesn't require address of arg as argument hence no `&` required
}
%s argument is used to scan a string of chars.
Note the difference between string of chars and array of chars. The string of chars in C needs to be terminated with ASCII Character 0 represented as \0 in char format, while the array of char is just a collection of letters which need not be terminated with \0.
The difference becomes more important when you try to perform some operation on strings such as printf, strcpy, strlen, etc.. These functions work on null character termination property of string.
For Example: strlen counts the characters in the string till it finds \0, to find out the length of string. Similarly, printf prints the string character by character until it finds the \0 character.
UPDATE:
Forgot to mention that scanf is not a good option to input char format. Use fgetc instead, with stdin as input FILE stream.
#include <stdio.h>
int main()
{
char *z;
int a;
printf("enter the no.");
scanf("%d",&a);
z = (char *) malloc(a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",z+i);
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%c\n",z);
}
return 0;
}
first error in your code is you have used "%s" instead of "%c".Second is it is impossible to store multiple values in one variable so instead of using variable use arrays.third is that you have told the user to enter the number of character that he/she wants to entered which you don't know.They can enter 1 also and 100000 also so the number of members in array is not defined.Better is to use specific number of characters in array.
finally i got the answer thank you for the help stackoverflow guys simply rocks ...
#include<stdio.h>
#include<malloc.h>
int main()
{
int a;
char *z=(char *)malloc(sizeof(a));
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%s",&z[i]);
}
printf("the entered letters are:\n");
for(i=0;i<a;i++)
{
printf("%c\n",z[i]);
}
return 0;
}

C for loop iteration

I have a problem writing code which does the following: declare a struct{char c; int x; } array and load it with scanf via a loop. After it's loaded, a call to function f will be made which will replace every occurrence of digits in the struct's component c with 0, and will return the sum of the digits replaced by zero.
Code and output are below and I have problem that the loop in the function f seems to iterate one time, and it gives out some really weird values.
This is an exam question so I have to use printf, scanf etc. Also I have that exam in an hour so any quick help is appreciated :)
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 2
struct par {
char c;
int x;
};
int f(struct par *niz) {
int i;
int n=0;
for(i=0; i<MAX; i++) {
if(isdigit(niz[i].c)) {
niz[i].c = niz[i].c-'0';
printf("niz[i].c = %d\n i = %d", niz[i].c, i);
n=n+niz[i].c;
niz[i].c='0';
}
}
return n;
}
void main() {
int n;
int i;
struct par niz[MAX];
printf("enter\n");
for(i=0; i<MAX; i++) {
scanf("%c", &niz[i].c);
scanf("%d", &niz[i].x);
}
n=f(niz);
for(int i=0; i<MAX; i++) {
printf("%d\n", niz[i].c);
printf("%d\n", niz[i].x);
}
printf("n = %d\n", n);
}
OUTPUT:
enter
2
2
2
niz[i].c = 2
i = 048
2
10
2
n = 2
When you press enter after the first input, the newline is not scanned by scanf and is left in the input buffer. When you then try to read the number scanf sees the newline and not a number so doesn't scan anything.
The simple solution to that is to add a leading space in front of the formats:
scanf(" %c", &niz[i].c);
scanf(" %d", &niz[i].x);
/* ^ */
This tells scanf to skip whitespace.
Use
niz[i].c = getchar();
instead of
scanf("%c", &niz[i].c);
or, you can use other better methods for getting char input discussed at SO,
Now,
You see second time you provided input only once, that is because the Enter you pressed after giving 2 as input to first char remained in input buffer, and was read on second iteration.
You are getting 10 as output, because, it is ASCII for \r, the Enter. It is not a digit, so not replaced to be '0'.
I am looking at your code (i am not using console for a decade, but ) here are some insights:
try to rename MAX with something else
do not know your IDE but sometimes MAX is reserved
and using it as macro can cause problems on some compilers
change scanf("%c", &niz[i].c) to scanf("%c", &(niz[i].c))
just to be shore that correct adsress is send to scanf
change scanf("%d", &niz[i].x) to scanf("%i", &(niz[i].x))
change "%d" to the correct value (this is main your problem)
"%c" for char
"%i" for int
Try to trace line by line and watch for improper variables change if above points does not help
weird values?
because you forgot "\n" after the line, so next print is behind the line "i = %d".
And, check return value of every function except ones that return void.

Resources