I want the programm to read the characters that are between two stars and if there are not two stars, it must print a respective message. For example if the input is 1abc*D2Efg_#!*34567, the output is between first tow stars (letters : 4, digits:1, other:3) any help will be appreciated
int main()
{
int ch,lowercase_lett,digits,other,uppercase_lett,asterisk;
lowercase_lett = 0;
uppercase_lett = 0;
digits = 0;
other = 0;
asterisk = 0;
printf("enter characters : ");
while((ch = getchar()) != '\n' && ch != EOF)
{
if(ch == '*')
{
asterisk++;
}
if(asterisk < 2)
{
printf("\ntwo asterisks not found\n");
}
else
{
if(ch>='a' && ch <= 'z')
{
lowercase_lett++;
}
else if(ch>='A' && ch <= 'Z')
{
uppercase_lett++;
}
else if(ch >='0' && ch <= '9')
{
digits++;
}
else
{
other++;
}
}
}
printf("\n%d letters %d digits and %d other" , lowercase_lett+uppercase_lett,digits,other);
return 0;
}
Count characters when exactly one asterisk has been found. Functions in ctype.h are useful to determine the type of characters.
#include <stdio.h>
#include <ctype.h>
int main(void){
int ch,lowercase_lett,digits,other,uppercase_lett,asterisk;
lowercase_lett = 0;
uppercase_lett = 0;
digits = 0;
other = 0;
asterisk = 0;
printf("enter characters : ");
while((ch = getchar()) != '\n' && ch != EOF)
{
if(ch == '*')
{
asterisk++;
if(asterisk>=2)
{
break;
}
}
else if(asterisk==1)
{
if(islower(ch))
{
lowercase_lett++;
}
else if(isupper(ch))
{
uppercase_lett++;
}else if(isdigit(ch)){
digits++;
}else{
other++;
}
}
}
if(asterisk<2)
{
printf("\ntwo asterisks not found\n");
}
else
{
printf("\n%d letters %d digits and %d other" , lowercase_lett+uppercase_lett,digits,other);
}
return 0;
}
You were almost there, but your code contains some lines in wrong places.
Look at my solution. I just tested and it works for your problem:
#include <stdio.h>
int main(){
int ch;
int lowercase_lett = 0;
int uppercase_lett = 0;
int digits = 0;
int other = 0;
int asterisks = 0;
printf("Enter characters: ");
while((ch = getchar()) != '\n' && ch != EOF)
{
if(asterisks == 2){
break; //End the search
}
else if(ch == '*'){
asterisks++; //Increment until we have 2 *
}
else if(asterisks == 1){
if((ch >= 'a') && (ch <= 'z')){
lowercase_lett++;
}
else if((ch >='A') && (ch <= 'Z')){
uppercase_lett++;
}
else if((ch >= '0') && (ch <= '9')){
digits++;
}
else{
other++;
}
}
}
if (asterisks >= 2){
printf("\n%d letters %d digits and %d other" , lowercase_lett+uppercase_lett,digits,other);
}
else{
printf("\ntwo asterisks not found\n");
}
return 0;
}
Related
This question already has answers here:
What is the behavior of integer division?
(6 answers)
Closed 1 year ago.
I'm doing homework and I have no idea why the %lf selector isn't working. I have to take a line of characters and determine if they can be a floating point or whole number and then print that number. Here's the code:
#include <stdio.h>
int main() {
char ch;
int isNumber = 1, dot = 0, negativeMult = 10;
double result = 0;
printf("\nEnter characters: ");
scanf("%c", &ch);
while (ch != 10) {
if ((ch >= '0' && ch <= '9')) {
if (dot) {
result = result + (ch - '0') / negativeMult;
negativeMult *= 10;
} else {
result = result * 10 + (ch - '0');
}
} else
if (ch == '.')
if (dot)
isNumber = 0;
else
dot = 1;
else {
isNumber = 0;
break;
}
scanf("%c", &ch);
}
if (isNumber)
printf("\nThe number is %lf", result);
else
printf("\nEntered characters are not able to be a number.");
return 0;
}
Edit: I forgot output. Sorry.
Input: Enter characters: 123.648
Output: The number is 123.000000
the error is here:
result = result + (ch - '0') / negativeMult;
(ch - '0') / negativeMult is integer division and it is always 0
it has to be
result = result + (double)(ch - '0') / negativeMult;
some more small errors amendments:
int main(void)
{
char ch;
int isNumber = 1, dot = 0, negativeMult = 10;
double result = 0;
int scanfresult;
printf("\nEnter characters: ");
scanfresult = scanf("%c", &ch);
while (ch != '\n' && scanfresult == 1)
{
if ((ch >= '0' && ch <= '9'))
{
if (dot)
{
result = result + (double)(ch - '0') / negativeMult;
negativeMult *= 10;
}
else
{
result = result * 10 + (ch - '0');
}
}
else if (ch == '.')
if (dot)
isNumber = 0;
else
dot = 1;
else
{
isNumber = 0;
break;
}
scanfresult = scanf("%c", &ch);
}
if (isNumber)
printf("\nThe number is %f", result);
else
printf("\nEntered characters are not able to be a number.");
return 0;
}
https://godbolt.org/z/nTKdjYsz8
I don't want my code to print other statements when the statement "is not a letter of the alphabet" is printed. Please help! I am still a noobie.
#include <stdio.h>
int main()
{
char ch;
int int_ch;
do {
printf("Type in an alphabet letter:");
scanf("%c%*c", &ch);
int_ch = (int)ch;
printf("Ch has ascii value %d\n", ch);
if ((ch >= 'a') && (ch <= 'z'))
{
int_ch = int_ch - 32;
}
else if ((ch >= 'A') && (ch <= 'Z'))
{
int_ch = int_ch + 32;
}
else
{
printf("Is not a letter of the Alphabet.");
}
//THIS HERE
ch = (char)int_ch;
printf("Ch is now %c\n", ch);
printf("Ch is now ascii value %d\n", int_ch);
} while (ch != '#');
return (0);
}
add continue is this else-statement
else
{
printf("Is not a letter of the Alphabet.");
continue;
}
The continue statement skips the current iteration of the loop and continues with the next iteration.
Insert the statement continue; after the printf() statement:
printf("Is not a letter of the Alphabet.");
continue;
which will let the program flow pass directly to the condition of the do while-loop:
Corrected code:
#include <stdio.h>
int main()
{
char ch;
int int_ch;
do {
printf("Type in an alphabet letter: ");
scanf("%c%*c", &ch);
int_ch = (int)ch;
printf("Ch has ascii value %d\n", ch);
if ((ch >= 'a') && (ch <= 'z'))
{
int_ch = int_ch - 32;
}
else if ((ch >= 'A') && (ch <= 'Z'))
{
int_ch = int_ch + 32;
}
else
{
printf("Is not a letter of the Alphabet.\n\n");
continue;
}
ch = (char)int_ch;
printf("Ch is now %c\n", ch);
printf("Ch is now ascii value %d\n", int_ch);
} while (ch != '#');
return (0);
}
Execution:
Type in an alphabet letter: 7
Ch has ascii value 55
Is not a letter of the Alphabet.
Type in an alphabet letter: (Waiting for data for another iteration)
I am trying to write a program that loops asking the user to continuously input either a float, int, or char and echo it back to them until they enter 'q', then the loop ends. I do not understand how to decipher between an int, char, or float before entering the loop. I have tried if (scanf("%c", ch)) and so on for float and int and that works great, but once I added the loop in it's messing me up. I have tried several different combinations, but I have still not found my answer.
Here is one attempt to show you exactly what I am trying to do:
char ch;
int num = 0;
float fl = 0;
printf("Enter a value: ");
while(ch != 'q') {
if (scanf("%c", &ch) && !isdigit(ch)) {
printf("You entered a character %c\n", ch);
}
else if (scanf("%d", &num)) }
printf("You entered an integer %d\n", num);
}
else if (scanf("%d", &num)) {
printf("You entered a floating point number %f\n", fl);
}
printf("Enter another value: ");
}
}
This keeps doing something strange and I cannot pinpoint my problem. Thank you in advance!
You cannot accomplish that with your approach. You can scan a line and parse it accordingly:
char line[128]; /* Create a buffer to store the line */
char ch = 0;
int num;
float fl; /* Variables to store data in */
int r;
size_t n; /* For checking from `sscanf` */
/* A `do...while` loop is best for your case */
do {
printf("Enter a value: ");
if(fgets(line, sizeof(line), stdin) == NULL) /* If scanning a line failed */
{
fputs("`fgets` failed", stderr);
exit(1); /* Exits the program with a return value `1`; Requires `stdlib.h` */
}
line[strcspn(line, "\n")] = '\0'; /* Replace `\n` with `'\0'` */
r = sscanf(buffer, "%d%zn", &num, &n);
if(r == 1 && n == strlen(line)) { /* If true, entered data is an integer; `strlen` requires `string.h` */
printf("You entered an integer %d\n", num);
}
else{
r = sscanf(buffer, "%f%zn", &fl, &n);
if(r == 1 && n == strlen(line)) { /* If true, entered data is a float; `strlen` requires `string.h` */
printf("You entered a floating point number %f\n", fl);
}
else{
if(strlen(line) == 1) /* If true, entered data is a character; `strlen` requires `string.h` */
{
ch = line[0];
printf("You entered a character %c\n", ch);
}
else{ /* Entered data is something else */
printf("You entered \"%s\"\n", line);
}
}
}
}while(c != 'q');
Disclaimer: I wrote the above code using a mobile and I haven't tested it.
Update (did not test and wrote with my mobile):
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
int main(void)
{
int c = 0;
bool random = false;
bool flag = true;
bool is_float = false, is_char = false, is_number = false;
do{
c = getchar();
if(c == EOF)
break;
if(!random)
{
if(isdigit(c))
{
is_number = true;
}
else if(c == '.')
{
if(is_number)
{
if(is_float)
{
random = true;
}
else
{
is_float = true;
}
}
else if(!is_number && !is_float && !is_char)
{
is_float = true;
}
}
else if(c == '-' && !is_float && !is_number && !is_char);
else if(isalpha(c))
{
if(is_char)
random = true;
else
{
is_char = true;
if(c == 'q')
flag = false;
}
}
else
{
random = true;
}
if((is_char && is_float) || (is_char && is_number))
random = true;
if(c == '\n' && !is_char && !is_float && !is_number)
random = true;
}
if(c == '\n')
{
if(random)
/* puts("You entered a random string!"); */
puts("Invalid input!");
else if(is_float)
puts("You entered a float!");
else if(is_number)
puts("You entered a number!");
else if(is_char)
puts("You entered a character!");
else
puts("Error!");
if(!flag && !is_number && !is_float && !random)
flag = false;
else
flag = true;
is_char = is_float = is_number = random = false;
}
}while(flag);
puts("Done");
return 0;
}
I have a file containing strings as well as numbers. Eg. my file Store-1.txt contains "coffee 2mug -4".
I need a c program to store the numbers only (i.e 2 and -4) by reading a file and saving just the numbers into an array.
i am not able to figure out how exactly to do this. Any suggestions please.
code is
#include <stdio.h>
int main(void)
{
char c,ch;
int flag=0;
FILE *fptr=fopen("Store-1.txt","r");
if(fptr)
{
while((c=fgetc(fptr))!=EOF)
{
if(c=='-' || c== '+')
{
ch=c;
flag=1;
}
if(c>='0' && c<='9')
{
if(flag == 1)
{
printf("%c",ch); flag =0;
}
printf("%c",c);
}
}
}
else
printf("Error : file not found");
system("pause");
}
read a file using fgetc() and printf() it if
c>='0' && c<='9'
Here is the full working code :
#include <stdio.h>
int main()
{
char c,ch;
int flag=0;
FILE *fp=fopen("file.txt","r");
if(fp)
{
while((c=fgetc(fp))!=EOF)
{
if(c=='-' || c== '+')
{
ch=c;
flag=1;
continue;
}
if(c>='0' && c<='9')
{
if(flag == 1)
{
printf("%c",ch); flag =0;
}
printf("%c",c);
}
else
flag=0;
}
}
else
printf("Error : file not found");
fclose(fp);}
#include <ctype.h>
#include <stdio.h>
int main(void)
{
int ch, n, sign;
sign = 1;
ch = getchar();
while (ch != EOF) {
if (ch == '-') {
sign = -1;
ch = getchar();
} else if (isdigit(ch)) {
n = 0;
do {
n = n * 10 + ch - '0';
ch = getchar();
} while (isdigit(ch));
n *= sign;
/*store n*/
} else {
sign = 1;
ch = getchar();
}
}
return 0;
}
I'm trying to print escape characters as characters or strings using this code:
while((c = fgetc(fp))!= EOF)
{
if(c == '\0')
{
printf(" \0");
}
else if(c == '\a')
{
printf(" \a");
}
else if(c == '\b')
{
printf(" \b");
}
else if(c == '\f')
{
printf(" \f");
}
else if(c == '\n')
{
printf(" \n");
}
else if(c == '\r')
{
printf(" \r");
}
else if(c == '\t')
{
printf(" \t");
}
else if(c == '\v')
{
printf(" \v");
}
}
but when i try it, it actually prints the escape sequence.
Escape the slashes (use " \\a") so they won't get interpreted specially. Also you might want to use a lookup table or a switch at least.
switch (c) {
case '\0':
printf(" \\0");
break;
case '\a':
printf(" \\a");
break;
/* And so on. */
}
Backslashes in string literals need to be escaped; instead of "\0", you need "\\0".
A lookup table might make this less painful:
const char *ecs[256] = {NULL}; // assumes ASCII - may not be a valid assumption
int c;
ecs['\0'] = "\\0";
ecs['\a'] = "\\a";
ecs['\b'] = "\\b";
...
while ((c = fgetc(fp)) != EOF)
{
if (ecs[c] == NULL)
printf("%c", c);
else
printf("%s", ecs[c]);
}
Yes, the majority of entries in ecs are going to be NULL; the tradeoff is that I don't have to worry about mapping the character value to array index.
For that we need to use double backslash.
Examples:
if(c == '\0')
{
printf(" \\0");
}
else if(c == '\a')
{
printf(" \\a");
}
else if(c == '\b')
{
printf(" \\b");
}
else if(c == '\f')
{
printf(" \\f");
}
else if(c == '\n')
{
printf(" \\n");
}
else if(c == '\r')
{
printf(" \\r");
}
else if(c == '\t')
{
printf(" \\t");
}
else if(c == '\v')
{
printf(" \\v");
}
Should work for you!
If you want to escape %d within printf to allow you to actually print the characters "%d":
printf("%%d");