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/
Related
The input of this function is s[] - char array and lim - max possible length of this array.
The function itself is used to determine the length of an inputed char array which is entered in the console.
The question is, what's the main idea of c != '\n' condition in for loop?
I guess it's used to break a loop. It's quite clear. But I can't get how it can be implemented if I don't type \n in my input.
Is that a terminator at the end of an array like \0?
If that's the case why should we use the if (c == '\n') condition after that?
The code:
int getline(char s[],int lim)
{
int c, i;
for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
As you press Enter a \n newline character is added to the input buffer, stdin, this means that this is the last character in the input buffer.
So it's only fitting the cycle continues on until getchar() retrieves this last character.
The cycle control states that c must be:
Different from \n.
Different fromEOF.
And the iterator i must be lower than lim - 1.
If one of these conditions is not met the cycle breaks, so it's possible that c is not equal to \n.
After that, if c is equal to \n, it will be added to s, the condition if (c == '\n') is there because, as stated, c might not be equal to \n, and in that case it shouldn't be added to s.
Lastly s must be null terminated (s[i] = '\0') so it can be properly interpreted as a string, aka a null terminated char array. \n is not a null terminator, \0 is.
The fact that \n is added is only because the implementer wanted it to be so, it's part of the implementation, it wouldn't have to be, but it is.
It can be useful in some cases, for instance fgets library function has a similar implementation, it adds \n to the containing buffer and then null terminates it.
Well you want to get a line. \0 terminates the string but a string can exist of multiple lines. As the function's name indicates you only want a single line. Lines are terminated with \n and after that a new line begins.
The condition
c != '\n'
is evaluated as true if a character different to new line character is encountered.
As you can understand, since it is a getline() implementation, it is a very good reason to stop reading from the input string.
Please note how, after this check ends the loop s[i] = '\0'; is executed in order to terminate the string one position after where previously the new line character was.
So, how do getline() works?
The core of that function is the for-loop
for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
The condition i < lim-1 && (c=getchar())!=EOF && c!='\n' means: "Assign to c a character got with `getchar() until...":
the read character is EOF
the read character is \n (newline)
the number of characters requested by the caller (lim) has been read
Because '\n'it is only one of the conditions -
it can be also EOF which author does not want to save and also chars number limit can be reached and we do not want to write the nul terminator out of the char array bounds
The nul termination is not related to any of those conditions and it always happens
If the character read c is a return to new line \n, then the for loop will stop, and the array will end with \n followed by \0.
And that's what the function is supposed to do, it's called getline(), and lines end with \n.
The logic is simply this:
In the for loop we're saying that when the user hit Enter, stop reading; so it stops and won't read the rest of the input. because the condition c!='\n' becomes false.
In the if statement, we're telling the program to continue reading; so "if" the user hits Enter, the program will start reading the rest of the input from where it left off and will start looping again.
The if statement is to prevent the loop from stopping and also a way of telling the program that there are separate lines in the input.
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.
{
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.
My program scans from input and prints all the capital letters used.
Im trying to print the original input from stdin at the end of my program too.
But when i use printf, it seems to skip the first part of the input expression, printing the remaining stuff in my character array. Please help me see where the problem lies. -comments in code-
#include <stdio.h>
int main(void){
char input[81];
int letters[91];
int i;
//initialize arrays input and letters
for (i = 0; i < 90; i++) letters[i] = 2;
for (i = 0 ; i < 80; i++) input[i] = 'a';
i = 0;
//reads into input array until EOF
while((scanf("%c",input)!= EOF)){
//checks input for characters A-Z
if((input[i]>= 'A' && input[i]<= 'Z'))
letters[input[i]] = 1;
}
//prints capital letters from input that occur at least once
for(i = 'A'; i < 'Z'; i++){
if (letters[i]==1)
printf("%c", i);} // this output works fine, the scan worked??
//print blank line
printf("\n\n");
// print input
printf("%s\n", input); //This is where the incorrect output comes from.
return 0;}
does my original input change? why?
did my input not get scanned correctly in the first place?
please respond quickly!
Here:
while((scanf("%c",input)!= EOF)){
you're only ever reading characters into input[0]. This is fine for what you're doing for letters, but obviously when you try to print out input, it's not going to work as you expect.
When you fix it, you'll also need to remember to add a terminating \0 after the last input character.
The scanf loop reads your input one character at a time, and stores that one character in input[0]. When the scanf loop is completely finished, input[0] contains the last character read, and the rest of input is untouched.
To repair, you need to include i++ at the end of the scanf loop.
By the way, it would be clearer (and more efficient) to fill the input buffer with a single call to fgets then loop through the input buffer with: for (i=0; buf[i]!='\0'; i++) { ... }
You must do
while((scanf("%c",&input[i])!= EOF))
{i++;}
instead of this
while((scanf("%c",&input)!= EOF))
{}
What you are doing is scan the character into the address of the first element int the array everytime, hence it gets overwritten again and again. Remaining part of the input[] array is not being accessed, and hence does not change
I need help understanding what are they really asking here.
I have written part of the program already.
Do I have to print the decimal value for the newline character and the tab character?
Why I can't get 10 pair per line all the time? Sometimes I get 10 pairs and another times not.
The assignment was:
Write a program that reads input as a stream of characters until
encountering EOF. Have the program print each input character and its
ASCII decimal value.
Note that characters preceding the space character in the ASCII
sequence are nonprinting characters. Treat them specially. If the
nonprinting character is a newline or tab, print \n or \t,
respectively. Otherwise, use control-character notation. For instance,
ASCII 1 is Ctrl+A, which can be displayed as ^A. Note that the ASCII
value for A is the value for Ctrl+A plus 64. A similar relation holds
for the other nonprinting characters. Print 10 pairs per line, except
start a fresh line each time a newline character is encountered.
This is what I have written:
#include <stdio.h>
int main(void)
{
int ch;
int i=0;
printf("Please enter some characters.\n\n");
while((ch=getchar()) != EOF)
{
if((i%10) == 0)
printf("\n");
if (ch == '\n')
printf( "\n\\n ");
else if (ch == '\t')
printf("\\t %d ", ch);
else if (ch < ' ')
printf("^%c %d ", ch+64, ch);
else
printf("%c %d ",ch, ch);
i = i+1;
}
return 0;
}
What they're asking for sounds very clear; here is some pseudo-code:
if (ch == '\n') print "\n %d", ch;
else if (ch == '\t') print "\t %d", ch;
else if (ch < ' ') { print "^"; print "%c %d", ch+'A', ch; }
else print "%c %d",ch, ch;
This is exclusive of formatting needed to make it look right; your code already has some formatting.
ASCII 0-31 are non-printing characters. Their respective control-character notations can be found at the ASCII Wikipedia page in the [b] column.
You will want to print the control-character notation for these characters, with the exception of 9 and 10, for which you will print \t and \n (backslash-t and backslash-n), respectively.
Another thing about your loop
if((i%10==0) || (ch == '\n'))
printf("\n");
These should be two separate statements. Make sure to escape your backslashes with an extra backslash beforehand as printf("\\n"); will actually print "\n" (backslash-n) whereas printf("\n") will just print an actual line feed, which I'm almost certain is not what your instructor is asking for here, except after each ten entries.
Have a look at the Wikipedia pages about ASCII, the caret notation (which is similar to control notation). I don't want to post the solution here. :D