This is for homework . Must use only getchar and putchar
int main(void) {
int pch; //first
int ch; //second
while(1){
pch=getchar();
ch=getchar();
if(((pch>='A' && pch<='Z')) && ((ch>='A' && ch<='Z'))){
putchar(ch);
putchar(pch);
}
if((pch>='A' && pch<='Z') && ch=='\n') putchar(pch);
if(pch=='\n' || ch=='\n') break;
}
return EXIT_SUCCESS;
}
I need to swap chars using getchar and putchar . For exemple
PARIS
APIRS
And it works , but i need to hit ENTER two times when i even number of letters 4,6,8... . How do i eliminate this behavior ? Is there some way to kill \n for getchar
I typed PAR, hit one time enter and got APR. I believe this is what you want.
Is there some way to kill \n for getchar?
You need to do something like this:
char1 = getchar();
getchar(); // To kill `\n`
char2 = getchar();
getchar(); // To kill `\n`
Source.
Also as suggested by mch, you can do:
if(pch == '\n') break; after pch=getchar();
So you should change your program to this:
#include <stdio.h>
int main(void) {
int pch; //first
int ch; //second
while (1) {
pch = getchar();
if (pch == '\n') // when you hit enter once, break the loop
break;
ch = getchar();
if (((pch >= 'A' && pch <= 'Z')) && ((ch >= 'A' && ch <= 'Z'))) {
putchar(ch);
putchar(pch);
}
if ((pch >= 'A' && pch <= 'Z') && ch == '\n')
putchar(pch);
if (pch == '\n' || ch == '\n')
break;
}
return 0;
}
Related
char ch;
int nr=0;
printf("\n: ");
ch = getchar();
while(ch != 'q' && ch != 'Q'){
ch = tolower(ch);
if(ch == 'a' || ch == 'e' || ch == 'o' || ch == 'i' || ch == 'u')
nr++;
printf("something");
ch = getchar();
}
printf("vocale: %d", nr);
its supposed to count the number of vowels until the user presses q or Q. it's such a silly program and yet i cant get past it.
Instead of using getchar
ch = getchar();
that also reads white space characters use scanf like
scanf( " %c", &ch );
Pay attention to the leading space in the format string. It allows to skip white space characters.
For example
while ( scanf( " %c", &ch ) == 1 && ch != 'q' && ch != 'Q'){
Also it will be more safer to write
ch = tolower( ( unsigned char )ch );
The problem is, that the input only gets flushed to your program whenever the user presses enter. Another reason why it seems not to work is, because you don't have a newline at the end of you output (printf("vocale: %d", nr); ), which causes the output not to be flushed to the terminal when the program ends. Fix this and your program works, but maybe not as you expect it to, because you still have to press enter. It will still only count to the first 'q' found.
int main() {
char ch;
int nr = 0;
printf(": ");
while(tolower(ch = getchar()) != 'q'){
ch = tolower(ch);
if(ch == 'a' || ch == 'e' || ch == 'o' || ch == 'i' || ch == 'u')
nr++;
}
printf("vocale: %d\n", nr);
}
The program:
: aeu q oi (here I pressed enter)
vocale: 3
the output window commandI am trying to use switch case in C to figure out the amount of characters, words, newlines in a user input. The code seems legit, no errors raised, however, the output does not work as expected. Please take a look and tell me what I did wrong. Thanks in advance! Here is the code:
#include <stdio.h>
int main()
{
char a, words = 1, characters = 0, newlines = 0;
printf("What do you have in mind? ");
a = getchar();
while ((a=getchar()) && a != EOF)
{
switch (a)
{
case '1':
if (a >= 'a' && a <= 'z' || a >= 'A' && a <= 'Z')
characters++;
printf("The amount of character is %c ", characters);
case '2':
if (a == ' ' || a == '\t')
words++;
printf("The amount of word is %c ", words);
case '3':
if (a == '\t')
newlines++;
printf("The amount of newlines is %c ", newlines);
default:
if (a == EOF)
break;
}
}
return 0;
}
you misunderstand what switch /case means. It does not means 'first case','second case' .. of some conditions, it means (in your specific situation), if the user just typed '1' then do this, it the users just typed '2' then do this,... well you are not typing 1 or 2 or 3.
Simply do this
while ((a=getchar()) && a != EOF)
{
if (a >= 'a' && a <= 'z' || a >= 'A' && a <= 'Z')
characters++;
printf("The amount of character is %c ", characters);
if (a == ' ' || a == '\t')
words++;
printf("The amount of word is %c ", words);
if (a == '\t')
newlines++;
printf("The amount of newlines is %c ", newlines);
}
Also you must change a to be an int
#include<stdio.h>
int
main ()
{
int ch_count = 0, line_count = 0, word_count = 0, choice;
char ch;
FILE *fp;
fp = fopen ("wordcount.txt", "r"); //make a seperate file "wordcount.txt" and Read the Test content from it.
if (fp == NULL) // Show error if previous step is not done i.e wordcount.txt file is not made.
{
perror ("FILE NOT FOUND.");
return (-1);
}
else // If file is opened properly then ask for NO. of counts.
{
printf ("Select the Following Option-------\n"
"1 - Number of Characters\n"
"2 - Number of Words\n"
"3 - Number of Lines\n");
scanf ("%d", &choice);
}
{
switch (choice) // switch to desired case as per choice of user.
{
case 1: // CASE 1 - To count the characters in the file.
{
while ((ch = fgetc (fp)) && ch != EOF)
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z')
ch_count++;
}
printf ("Number of Characters : %d\n", ch_count);
break;
case 2: // CASE 2: To count total number of words
while ((ch = fgetc (fp)) && ch != EOF)
if ((ch == ' ') || (ch == '\t') || (ch == '\n') || (ch == '\0'))
{
word_count++;
}
printf ("Numbers of Words : %d\n", word_count);
break;
case 3: // CASE 3: To count total number of lines
while ((ch = fgetc (fp)) && ch != EOF)
if ((ch == '\n') || (ch == '\0'))
{
line_count++;
}
printf ("Numbers of lines : %d\n", line_count);
break;
} //switch closed
}
fclose (fp); //file closed
return 0;
}
I've encountered a problem when validating a single-char scanf input in C and I cannot find an existing solution that works...
The scenario is: a method is taking a single letter 'char' type input and then validating this input, if the criteria is not met, then pops an error message and re-enter, otherwise return this character value.
my code is:
char GetStuff(void)
{
char c;
scanf("%c", &c);
while(c != 'A' || c != 'P')
{
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%c", &dtChar);
}
return c;
}
however, i got the infinite loop of error message no matter what input I type in. I read some other posts and guess it's the problem that %c specifier does no automatically get rid of the newline when I hit enter, and so far I have tried:
putting a white space before/after %c like:
scanf(" %c", &c);
write a separate method or include in this GetStuff method to clean the newline like:
void cleanBuffer(){
int n;
while((n = getchar()) != EOF && n != '\n' );
}
Can anyone help me with this problem please? Thank you in advance.
Please consider the following snippet:
#include <stdio.h>
#include <ctype.h>
char GetStuff(void)
{
char c;
do {
printf("Please enter A for AM or P for PM: ");
scanf ("%c", &c);
// clean input buffer (till the end of line)
while(getchar()!='\n');
} while(toupper(c) != 'A' && toupper(c) != 'P');
return c;
}
int main(void)
{
printf("Your input is'%c'\n", GetStuff());
return 0;
}
Note the points:
condition while(c != 'A' || c != 'P') will be always true (just because one character cannot be 'A' and 'P' at the same time), so use while(c != 'A' && c != 'P') instead
No need for two scanf if you use do..while loop
After entering a char with scanf it is recommended to clean all characters from buffer, e.g. with while(getchar()!='\n'); (this will clean all input including incorrect and redundant characters)
use toupper to avoid making 4 comparison (actually single c=toupper(c) inside loop can minimize your while as while(c != 'A' && c != 'P') )
UPDATE:
To add message "Invalid input" and adding some other useful improvement subjected befor... new code is as:
#include <stdio.h>
#include <ctype.h>
void CleanBuffer(){
int n;
while((n = getchar()) != EOF && n != '\n' );
}
char GetStuff(void)
{
char c;
do {
printf("Please enter A for AM or P for PM: ");
scanf (" %c", &c);
c = toupper(c); // here letter become uppercase
CleanBuffer();
} while( (c != 'A' && c != 'P')?printf("Invalid input! "):0 );
return c;
}
int main(void)
{
printf("You have entered: %c\n", GetStuff());
return 0;
}
Note: function will return 'A' or 'P' in uppercase, so if this is not needed change the code as in example before update (use two toupper and do not change c after scanf). Also you can use tolower as an option (of course with comparing to 'a' and 'p').
#include <stdio.h>
char GetStuff(void) {
char c;
scanf("%c", &c);
getchar();
while ((c != 'A') && (c != 'a') && (c != 'P') && (c != 'p')) {
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%c", &c);
getchar();
}
return c;
}
int main(void) {
printf("Calling GetStuff()...\n");
char x = GetStuff();
printf("User entered %c\n", x);
return 0;
}
You are using while (c != 'A' || c != 'P') as your loop conditional, but this will always return true. What you meant to use is the && "and" operator, instead of the || "or" operator.
Also, call getchar() after your scanf statements, to capture the newline. This should work the way you want it to.
Inside loop you are taking input in dtChar but your loop condition checks variable c which is not updated in the loop, that is causing infinite loop
Also you would change your condition
while(c != 'A' || c != 'P')
to
while(c != 'A' && c != 'P')
If you want user to enter either 'A' or 'P'
Another possible solution. As others mentioned the condition was to be done with &&. Anyway the big problem is how to remove what's left on the console input line. Since the console works by lines, we remove everything up to the next '\n'. If the user already left something on the input line before calling GetStuff(), it would be useful to add a call to SkipRestOfTheLine() before the while loop.
In general I suggest to start with a while(1) loop, before making it nicer (such as in the cleanBuffer() you posted).
#include <stdlib.h>
#include <stdio.h>
void SkipRestOfTheLine(void)
{
while (1) {
int c = fgetc(stdin);
if (c == EOF || c == '\n')
break;
}
}
char GetStuff(void)
{
while (1) {
int c = fgetc(stdin);
if (c == EOF)
exit(EXIT_FAILURE); // Deal with this case in an appropriate way
if (c == 'A' || c == 'P')
return c;
printf("invalid input, enter again (A for AM or P for PM): ");
SkipRestOfTheLine();
}
}
int main(void)
{
char c = GetStuff();
return 0;
}
try this,
char GetStuff(void)
{
char c;
scanf("%c", &c);
while (((c != 'A') || (c != 'a')) && ((c != 'P') || (c != 'p'))==1)
{
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%c", &dtChar);
}
return c;
}
I hope this works, some time because of not given proper bracket it is stuck in the loop.
#include <stdio.h>
int main(){
char c;
do{
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%s", &c);
}while ((c != 'A') && (c != 'P'));
return 0;
}
I realised that if the input is a word starting with 'y' or 'n', it will escape the loop. How can I restrict the loop such that it will continue looping unless the input is a single character?
do
{
printf("Do you want to try again? (Y/N): ");
fflush(stdin);
scanf("%c", &repeat);
repeat = toupper(repeat);
if (repeat != 'Y' && repeat != 'N')
printf("Invalid answer. Please enter 'Y' or 'N'.\n\n");
} while (repeat != 'N' && repeat != 'Y');
like this:
#include <stdio.h>
#include <ctype.h>
int main(void){
char repeat[3] = {0};//3 : one character + one character + NUL
do{
printf("Do you want to try again? (Y/N): ");fflush(stdout);
if(EOF==scanf("%2s", repeat)){ *repeat = 'N'; break; }
*repeat = toupper(*repeat);
if (repeat[1] || *repeat != 'Y' && *repeat != 'N'){//repeat[1] != '\0'..
printf("Invalid answer. Please enter 'Y' or 'N'.\n\n");
scanf("%*[^\n]");scanf("%*c");//clear upto newline
*repeat = 0;
}
} while (*repeat != 'N' && *repeat != 'Y');
puts("Bye!");//try agein or see ya, bye
return 0;
}
First fflush(stdin); does not make sense except in Microsoft's world.
Then, the scanf family function returns a value which is the number of input token successfully decoded and that return value should always be controlled. And %c should be used with caution because it can return a blank character (space or newline) remaining in buffer while %s only return printable characters. With those remarks you code could become:
repeat = '\0';
do
{
char dummy[2], inp[2];
printf("Do you want to try again? (Y/N): ");
// fflush(stdin);
if (1 == scanf("%1s%1s", inp,dummy) repeat = toupper(inp[0]);
if (repeat != 'Y' && repeat != 'N')
printf("Invalid answer. Please enter 'Y' or 'N'.\n\n");
} while (repeat != 'N' && repeat != 'Y');
Alternatively to using scanf() one can use fgets() to read a line and then do the parsing one self:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char repeat = '\0';
do
{
int input_valid = 0; /* Be pessimistic. */
char line[3] = {0};
puts("Do you want to try again? (Y/N):");
do /* On-time loop, to break out on parsing error. */
{
if (NULL == fgets(line, sizeof line, stdin))
{
break; /* Either fgets() failed or EOF was read. Start over ... */
}
if (line[1] != '\0' && line[1] != '\n')
{
break; /* There was more then one character read. Start over ... */
}
line[0] = toupper(line[0]);
if (line[0] != 'Y' && line[0] != 'N')
{
break; /* Something else but Y or N was read. Start over ... */
}
input_valid = 1;
} while (0);
if (input_valid == 0)
{
int c;
do /* Flush rest of input. if any. */
{
c = getc(stdin);
} while (EOF != c && '\n' != c);
fprintf(stderr, "Invalid answer. Please enter 'Y' or 'N'.\n\n");
}
else
{
repeat = line[0];
}
} while ('\0' == repeat);
printf("The user entered: '%c'\n", repeat); /* Will only print either Y or N. */
return EXIT_SUCCESS;
}
I'm doing a program that is asking the user to enter a stream of characters and printing out the number of uppercase and lowercase letters. I'm trying to do it with a function, but having some trouble printing it..for every character input im entering im getting 0, 0
Would appreciate your help to understand what am I doing wrong:
#include <stdio.h>
#include <ctype.h>
int case_letters(int ch);
int main(void)
{
int x;
printf("please enter a some characters, and ctrl + d to see result\n");
case_letters(x);
return 0;
}
int case_letters(int ch)
{
int numOfUpper = 0;
int numOfLower = 0;
while ((ch = getchar()) != EOF)
{
if ((ch = isdigit(ch)) || ch == '\n')
{
printf("please enter a valid character\n");
continue;
}
else if ((ch = isupper(ch)))
{
numOfUpper++;
}
else if ((ch = islower(ch)))
{
numOfLower++;
}
}
return printf("%d, %d", numOfUpper, numOfLower);
}
All of your if statements assign different value to ch and do not check ch's value.
For example, if you enter a correct char, this
if ((ch = isdigit(ch)) || ch == '\n')
will assign 0 to ch, because isdigit(ch) will return 0. I guess you need
if ( isdigit(ch) || ch == '\n')
Same for islower and isupper.
if ((ch = isdigit(ch)) || ch == '\n')
^-- assignment, not equality test.
You're trashing the value of ch with the return value of isdigit(), and isupper(), and islower(), so that the original user-entered value is destroyed as soon as you do the isdigit test.
Try
if (isdigit(ch) || ch == '\n')
else if (isupper(ch))
else if (islower(ch))
instead. No need to preserve the iswhatever values.