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");
Related
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;
}
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 read a graph from file, I got on the first line the nodes, and I made a code that reads the nodes in the vector until the end of the line, then on the second like I got the arcs, in the (%d %d) format. My problem is that when I try to read the nodes, it skips the first number, third, and so on. And I cannot figure out why.
Here is my code:
void readGraph() {
int i=0, j, node1, node2, n,check1, check2,c;
char nodes[MAXN];
FILE *f;
f = fopen("data.in","r");
if (f == NULL) {
printf("Error in opening file!");
}
else {
while ((c = fgetc(f)) != EOF) {
if ( c != ' ') {
fscanf(f, "%d", &(nodes[i]));
printf("%d, %d\n",i,nodes[i]);
i++;
}
if (c == '\n')
break;
}
}
while (fscanf(f,"(%d %d)", &node1, &node2)) {
if ( c != ' ')
fscanf(f, "(%d %d) ", &node1, &node2);
if (c == '\n')
break;
}
fclose(f);
}
Also, my data.in:
1 2 3 4 5 6
(1 3) (2 3) (3 4) (3 5) (3 6) (4 6) (5 6)
Any help will be much appreciated. Thanks!
I am guessing, fgetc reads byte by byte, and fscanf("%d") reads 4 bytes at a time, so this could cause some issue.
while ((c = fgetc(f)) != EOF) {
if ( c != ' ') {
fscanf(f, "%d", &(nodes[i]));
printf("%d, %d\n",i,nodes[i]);
i++;
}
if (c == '\n')
break;
}
Here you read twice from f (fgetc(f) is discarded)
For the arcs (code below) there's also a problem, you test c but you're not reading it any more
while (fscanf(f,"(%d %d)", &node1, &node2)) {
if ( c != ' ')
fscanf(f, "(%d %d) ", &node1, &node2);
if (c == '\n')
break;
}
try this solution and you can see my c comments:
void readGraph() {
int i=0, j, node1, node2, n,check1, check2,c;
char nodes[128];
FILE *f;
f = fopen("data.in","r");
if (f == NULL) {
printf("Error in opening file!");
}
else {
while (((c = fgetc(f)) != EOF) && (c != '\n')) {
if ( c != ' ') {
nodes[i] = c;
/*fscanf(f, "%d", &(nodes[i]));*/ // you loose read c value when you read again without using value
printf("%d, %c\n",i,nodes[i]);
i++;
}
/*if (c == '\n')
break;*/
/* You loop 1 extra time */
}
}
while (fscanf(f,"(%d %d)", &node1, &node2)) {
if ( c != ' ')
fscanf(f, "(%d %d) ", &node1, &node2);
if (c == '\n')
break;
}
fclose(f);
}
void readGraph(void){
int i = 0, j, node1, node2, n, check1, check2, c;
int nodes[MAXN];
FILE *f;
f = fopen("data.in","r");
if (f == NULL) {
printf("Error in opening file!");
return ;
}
while ((c = fgetc(f)) != EOF) {
if( c == ' ')
continue;
else if( c == '\n')
break;
else {
ungetc(c, f);//It is too reading. So Return the character to the stream.
fscanf(f, "%d", &nodes[i]);
printf("%d, %d\n", i, nodes[i]);
i++;
}
}
while (2 == fscanf(f,"(%d %d) ", &node1, &node2)) {
printf("(%d, %d)\n", node1, node2);
}
fclose(f);
}
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;
}
My task is to get an input, print out the character and the ASCII value, and to present them each 8 for 1 line. For every input I'm typing I'm getting also the value of the newline character and I don't want to print it.
This is my code:
#include <stdio.h>
int main()
{
char ch;
int count = 0;
printf("please type an input:\n");
while ((ch = getchar()) != '#')
{
++count;
printf("%c=%d ", ch, ch);
if (count%8 == 0) printf("\n");
}
}
You can use another getchar() right after reading the first one:
while ((ch = getchar()) != '#')
{
getchar(); // To eat the newline character
// Rest of code
}
Or you can use scanf() and rewrite the loop equivalently:
while (scanf(" %c", &ch)==1)
{
if(ch != '#')
{
++count;
printf("%c=%d ", ch, ch);
if (count%8 == 0)
printf("\n");
}
}
int main()
{
char ch;
int count = 0;
printf("please type an input:\n");
while (1) {
ch = getchar();
if (ch == '#') break;
if (ch == '\n') continue;
printf("%c=%d ", ch, ch);
if (!(++count%8)) printf("\n");
}
}