{
char ch;
int count, lineCount;
count = 0;
lineCount = 0;
printf("Please enter one alphabet\n");
for (lineCount = 0; (ch = getchar()) != '\n'; lineCount++)
{
putchar(ch-'0');
printf("\n");
for (count = 0; count <= (ch - '0'); count++)
printf("%c \n", ch);
}
return 0;
}
This is my code so far. I need to do more stuff later but I'm just taking one step at a time. So I'd enter a letter. For example, d.
I put that putchar there to check that ch-'0' equals to the number I want. It does. d comes out to 4.
So in theory, I thought this code would print d out 4 times. But in reality, it printed it out a good 30-40 times.
It's the same with any other letter. It prints out a good 40 times. Plus, the count has no effect. I initialized it with a 5, which is obviously greater than 4. It still prints out like 40 times.
I haven't used for loops much. I know the concept, but I perhaps I'm making a huge C language mistake.
What's wrong here??
haha well I only copied the parts that count. I have the main.
And isn't 4 the integer value for 'd' - '0'? that's what it printed out as in that putchar statement and I actually tried changing it into int, but it made no difference. Well, not saying you are wrong at all. I'm the one that's wrong obviously. But that was my thinking behind it.
Please, can you explain the logistics behind it and what I should do?
Well, based on Please enter one alphabet you can reduce your for loop to
for (lineCount = 0; (ch = getchar()) != '\n'; lineCount++)
{
putchar(ch);
printf("\n");
printf("From Printf: %c \n", ch);
}
Note: ch - '0' is usually used to get the integer value of the char digit(s), '0' to '9'.
'd' - '0' is not 4. If you refer to an ASCII chart, you'll see that the value for 'd' in decimal is 100 and the value for '0' in decimal is 48, so I would expect the inner loop to repeat 100-48 = 52 times.
Since you did a putchar, it sent a byte having the decimal value 52 to the output, which happens to correspond to the ASCII character '4'.
Note that if you typed '4' instead of 'd', you should see it loop 4 times.
The basic issue is that of the relationship between quantitative values and representations of values in a given character set.
Related
Novice C student here.
Could someone please explain why isdigit() is returning true for values 10+?
I'm doing a pretty basic assignment regarding a guessing game and must use isdigit() to inform user if he has entered a number 1-10 or not.
The program seems to be running fine otherwise, I just would like to know the reasoning behind isdigit() returning true for values 10+.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
int main()
{
int iRandomNum = 0;
char cResponse = '0';
srand(time(NULL));
iRandomNum = (rand() % 10) + 1;
printf("\nGuess a number between 1 and 10: ");
scanf("%c", &cResponse);
if (!isdigit(cResponse) || cResponse<'0'+1)
printf("\nYou did not enter a number 1-10");
else if ((cResponse - '0') == iRandomNum)
printf("\nCorrect!");
else
{
printf("\nSorry, you guessed wrong\n");
printf("The correct guess was %d\n", iRandomNum);
}
return 0;
}
If you add a printf to log the value of cResponse, the problem will become apparent very quickly:
printf("\nGuess a number between 1 and 10: ");
scanf("%c", &cResponse);
printf("cResponse is %c\n", cResponse);
outputs:
Guess a number between 1 and 10: 10
cResponse is 1
As you can see, only the first character is stored in cResponse (which makes sense, as it's just a single character), and since that first character is a digit, your isdigit() call returns true.
If you want to read numbers greater than 10, you can read to an int instead:
int cResponse = 0;
printf("\nGuess a number between 1 and 10: ");
scanf("%d", &cResponse);
printf("cResponse is %d\n", cResponse); // prints '10' if I type '10'
Note that you cannot use isdigit() in this case, although you can still easily check your bounds using if (cResponse >= 0 && cResponse <= 10).
You are passing a char to isdigit, which can only hold a single character. Thus, while you may be typing in 10, only the first character (which is a digit) is getting into cResponse.
Instead of reading the users input as a char, read it in as an int. This way you can just use if(guess >= 1 && guess <= 10). Since you need 10 as part of the range of inputs a char (which is a single character) wont do. You will either need to use a string (which will make things more complicated) or just use an int.
I'm working through some of the exercises in K&R. Exercise 1-6 asks for verification that the expression getchar() != EOF is either 0 or 1. I understand why it is, but the code I wrote to prove it didn't work as expected. I wrote the following two snippets:
Version 1:
int main(void)
{
int c;
while (c = getchar() != EOF)
{
putchar(c);
}
printf("%d at EOF\n", c);
return 0;
}
Version 2:
int main(void)
{
int c;
while (c = getchar() != EOF)
{
printf("%d\n", c);
}
printf("%d at EOF\n", c);
return 0;
}
My questions:
When I type in a character and hit enter with version one, why do I not see either a 0 or 1 on the screen? Instead, my cursor moves to the first position on next line, which is otherwise empty. I though putchar would send c to stdout.
While the use of printf in the second version does produce a 0 or 1 appropriately, it duplicates the 1 for each non-EOF character (I see the number 1 on two consecutive lines for each character I input). Why?
Many thanks in advance for your thoughts. If there is a reference that you think would help, please send a link.
CLARIFICATION:
I know I'm assigning c a value of either 0 or 1. That's what I want to do, and it's what the exercise wants. That's also why I don't have parentheses around c = getchar(). My question deals more with understanding why the output isn't what I had expected. Sorry for any confusion.
The assignment operator = has lower precedence than the inequality operator !=.
So this:
while (c = getchar() != EOF)
Is parsed as:
while (c = (getchar() != EOF))
So then c is assigned the boolean value 1 if getchar is not EOF and 0 if it does return EOF.
As a result, the first program print the character for the ASCII code 1, which is a non-printable character. That's why you don't see anything. The second program, using the %d format specifier to printf, converts the number 1 to its string representation.
You need parenthesis to have the result of getchar assigned to c:
while ((c = getchar()) != EOF)
EDIT:
To further clarify the output you're getting, in both programs the variable c has the value 1 inside of each while loop. The difference here is that putchar is printing the character with the ASCII value of 1 (an unprintable character), while printf with %d print the textual representation of the value 1, i.e. 1.
If you changed the printf call to this:
printf("%c", c);
You would get the same output as using putchar.
As for the printing of 1 twice for each character, that is because you're actually entering two characters: the key you press, plus the enter key. When reading from the console, the getchar function doesn't return until the enter key is pressed.
I was writing some code where I was getting an unexpected output in one part of the program, which in turn disrupted the entire system.
The code can be simplified and shortened to:
char ch;
printf("Enter Number: ");
while ((ch = getchar()) != '\n') {
if (ch >= 65 && ch <= 67) {
ch = 2;
}
putchar(ch);
}
As per the code above, I am trying to print a character/integer sequence of the user's choice. The numbers should remain unchanged whereas if the user enters letter A, then this should print 2.
Expected Output
Enter Number: 23-AB
23-22
Actual Output
Enter Number: 23-AB
23-☺☺
Once confronted with this problem, I decided to tweak some things and came up with the following code which worked perfectly. It uses the same approach but produces different output:
char input;
printf("\nEnter Number: ");
while ((ch = getchar()) != '\n') {
switch (toupper(ch)) { //toupper function not really needed since I am expecting the user to enter upper-case letters ONLY
case 'A': case 'B': case 'C':
printf("2");
break;
default:
putchar(ch);
}
}
Expected Output
Enter Number: 23-AB
23-22
Actual Output
Enter Number: 23-AB
23-22
I am unable to comprehend why I am failing to convert the ASCII value of the characters entered in the first code to a single integer. What is the reason for this difference in the outputs? I have simply changed the type of controlling expression, from if-statement to a switch-statement (or so I think). How can I alter the first code to provide me with the same output as the second code?
In the first version, setting ch=2; makes ch the character with ASCII value 2, not the character 2. ch=0x32; in your first version would probably work, since ASCII 50 = 0x32 is character 2. Even easier (and better, as Weather Vane points out) is ch='2';.
In your second version, you are using printf("2"). As a result, the compiler is producing the ASCII value for you when it processes the string "2", just as it would for ch='2';. Try printf("%d\n",'2'); and you should see 50.
Program take a text and n value. Add this n value each character. (Don’t add n numeric characters).
For exemple:
n=1
input:
akm101
output:
bln101
I have tried this but didn't execute.
while( letter != EOF ){
fscanf(inp, "%c", &letter);
if(47 < letter && letter < 58)
printf("%c",letter);
else
printf("%c", letter+n);
}
Since this is probably homework, where the objective is learning rather than producing a correct answer, I'll offer some guidance.
Loop through each character in the string.
If the character is a letter, increment the value of the character at that position by one
Output the result of this loop.
http://www.asciitable.com/
Let's say that we have a very simple code that begins like:
#include <stdio.h>
int main() {
char c;
int x;
printf("Num here: ");
c = getchar();
x = 0;
while (c!=EOF) {
x = c - 48; //to convert x from ASCII
In this program, I'm trying to get the user to type a number (ex. 42) and am trying to add the ones digit to the tens (and to the hundreds, etc.); I'm having a lot of trouble understanding how you can get the while loop to go back to the loop until the end of the number.
So, I need a lot of help understanding how I can get the loop to read until the end of the character, read the char input the user puts in as a number (42), and then, treat the numbers individually using just getchar().
Normally, you'd use:
int c; // Because getchar() returns an int, not a char
int x = 0;
while ((c = getchar()) != EOF)
{
if (isdigit(c))
x = x * 10 + (c - '0');
else
...
}
This reads a character each time it reaches the top of the loop. You get the loop to go back by running into the brace at the end of the loop (or, occasionally, by using a continue statement). You might exit the loop with a break, for example if you read some character that can't be part of a number.
If the user types 42 (followed by Enter), then you first read c == '4' and then c == '2' and then you read newline '\n'. For every digit from '0' to '9', digit - '0' yields the number corresponding to the digit. The newline can't be part of the number, so you either put it back with ungetc(c, stdin) or break the loop when you've read it.
Beware of overflow if the user types 43219876543 where you expected just 42 (and int is a 32-bit quantity).
You could write the loop condition as:
while ((c = getchar()) != EOF && isdigit(c))
or even:
while (isdigit(c = getchar()))
I'd be extremely reluctant to actually put the latter into production code but it is, in theory, safe.
How could I treat each number individually so that I can use the entirety of the numbers later on? So that if the user types 10 20 30, I can multiply 10 by 20, then (10*20) by 30?
Wheels within wheels — or loops within loops. You'll need to specify your criteria a bit. If the user types 1 you want the answer 1; if they type 1 2, you want 2; if they type 1 2 3, you want 6; and so on (where these are all the numbers on a single line of input). You'll need an outer loop that skips over blanks and tabs, then uses the inner loop to read a number, and then multiplies the current product (initial value 1) by the new number, and after the outer loop, you'll print the product. This will print 1 for an empty line; maybe that doesn't matter (and maybe it does).
Here's some code that approximates what is appropriate:
#include <ctype.h>
#include <stdio.h>
int main(void)
{
int c;
while ((c = getchar()) != EOF && c != '\n')
{
int product = 1;
while (c != EOF && c != '\n')
{
while (isspace(c))
c = getchar();
int number = 0;
while (isdigit(c))
{
number = number * 10 + (c - '0');
c = getchar();
}
printf("Number: %d\n", number);
product *= number;
}
printf("Product: %d\n", product);
}
return 0;
}
I also tried a version with a slightly different 'skip' loop:
while (c != EOF && c != '\n' && !isdigit(c))
c = getchar();
Both work OK on sane inputs. Empty lines are treated as end of input; lines containing blanks are not. If you input 1a2b3c with the second condition, you will get the output 0; with the first, you get an infinite loop. There is no overflow protection; don't try doing factorial 20 and expect the correct answer (with 32-bit int). Tweak to your heart's content.
Your code :
#include <stdio.h>
#include<ctype.h>
int main() {
int c;//getchar() returns integer
int x;
printf("Num here: ");
x=0;
//As #Jonathan Leffler suggested ,
//usage of while loop like this is very helpful the moment you press Enter loop breaks.
while (isdigit(c = getchar())) //isdigit is a function from ctype.h checks for Entered character is digit or not
x = x*10 + c - 48; //here '0'==48
printf("%d",x);
}
when you enter 42
loop rotates two times for c==4 and c==2
c==4
x=0*10+'4'-48 //here '4'==52 ==> x=0+52-48 ==>x=4
c==2
x=4*10+'2'-48 //here '2'==50 ==> x=40+50-48 ==>x=42
to add ones digits to tens and then hundreds ... if you want to add digits in input number use this below while loop
int sum=0,num;
//read num
while(num>0)
{
sum=sum+num%10; //get the last digit and add to sum
num=num/10; //reduce last digit of num
}
Read in character by character and convert that to a numeral using the while loop in Jonathan's answer. Every time you read a numeral, simply multiple your current sum by 10, and add the number. That way by the time you read the last numeral and add it in, you'll have the correct number.
Sometimes the way we think a problem should be solved, can be solved in a different method when all of the languages capabilities are considered.
#include <stdio.h>
int main() {
int x;
printf("Num here: ");
scanf("%d", x);
}
implements the same functionality as your program.