I am unable to find out if the ternary operator is present or not through following code.. Plz help.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void one();
int main()
{
FILE *fp;
fp=fopen("C:/Users/HP/Documents/NetBeansProjects/CD2/1.txt","r");
char c;
void one()
{
char c;
while((c=fgetc(fp)!=EOF))
{
if(c==':')
{
printf("\nThe ternary operator present");
return;
}
}
}
while((c=fgetc(fp))!=EOF)
{
printf("\n-->%c",c);
if(c=='?')
{
one();
}
}
return 0;
}
I want to know why this code doesn't work and say if the ternary operator is present or not in file 1.txt
The output shows all characters till '?' if we print them, but why it's not finding for a colon ':' ?
The exit condition of the while loop may be the problem. = has lesser precedence than != operator. So
(c=fgetc(fp)!=EOF)
gets evaluated like
(c= (fgetc(fp)!=EOF) )
See this for the precedence of various operators in C.
You could do
while((c=fgetc(fp))!=EOF)
instead. First assign the return value of fgetc() to c and then do the comparison.
ie, the variable c gets the result of the comparison which means the value is either 0 or 1.
Your program should be checking for the ? and the other operands as well.
See this.
A simple check may not be enough for cases like the 'operator' being part of a string like
char str[]="the ternary operator is ?:";
Checking for the occurrence in such cases is a bit complex.
Edit:
As Jens pointed out, fgetc() returns an int not a char. So make c an int instead of a char.
See this post.
Related
This is a program for copying content from one file to other file. How to specify EOF in online compiler so that my code will run as expected??
Link for online editor--->
https://www.jdoodle.com/c-online-compiler
//code for copying content--->>
#include "stdio.h"
int main()
{
char ch;
FILE *p,*q;
p=fopen("data.txt","w");
while(ch=getchar()!=EOF)
{
putc(ch,p);
}
fclose(p);
p=fopen("data.txt","r");
q=fopen("newdata.txt","w");
while(ch=getc(p)!=EOF)
{
putc(ch,q);
}
fclose(p);
fclose(q);
q=fopen("newdata.txt","r");
while(ch=getc(q)!=EOF)
{
printf("\n%c",ch);
}
}
There are two problems with the expression ch=getchar()!=EOF:
The first is that getchar returns an int. This is actually important for the EOF comparison.
The second problem is about operator precedence. You expression is really ch = (getchar() != EOF). That is, you assign the result of the comparison (which is an 1 or 0) to the variable ch.
To solve the first problem, define the variable ch as an int.
To solve the second problem use explicit parentheses: (ch = getchar()) != EOF.
#include <stdio.h>
#include <conio.h>
void main ()
{
clrscr () ;
char a [5];
puts ("K?");
gets (a);
fflush (stdin);
if (a = ("K"))
{
puts (a);
}
else
{
puts ("BAE");
}
getch ();
}
The 10th line shows an Lvalue error while compiling, please help. this is my first program ever and this is my first day ever on coding and I'm self teaching.
fflush(stdin) is Undefined Behavior
the comparison operator in C is a ==; = is the assignment operator. You can't assign anything to an array, so an error is thrown
you can compare strings using strcmp() from <string.h>; == just compares their addresses
I think that instead of the assignment in the if statement
if (a = ("K"))
you mean a comparison.
Nevertheless arrays do not have the comparison operator. You have to compare arrays element by element yourself. For character arrays there is function strcmp declared in header <string.h>.
Thus the valid code can look like
Also you should not use fflush function with standard input. Otherwise the program has undefined behaviour,
#include <string.h>
//...
if ( strcmp( a, "K" ) == 0 )
//...
There are two mistakes in this line
if (a = ("K"))
First, you are using = where you meant ==. But that is wrong anyway, you cannot test for string equality in C. It has to be something like this, which tests the first character of the string and its terminator
if (a[0] == 'K' && a[1] == '\0')
or, you can use a library function
#include <string.h>
...
if (strcmp(a, "K") == 0) {
// are the same string.
}
I'm new to C
i'm asked to check if the format of the text file input is right or not!
the file should have lines like this :
1-float
2-('+'/'*'/'-')
3-flaot
4-'='
5-the result of the above operation
6-';'
I read the file and place each char in an array but have no idea what to do next
here is my code
#include <stdio.h>
#include <conio.h>
/*Max number of characters to be read/write from file*/
#define MAX_CHAR_FOR_FILE_OPERATION 1000000
int main()
{
char *filename = "D:\input.txt";
FILE *fp;
char text[MAX_CHAR_FOR_FILE_OPERATION];
int i;
fp = fopen(filename, "r");
if(fp == NULL)
{
printf("File Pointer is invalid\n");
return -1;
}
//Ensure array write starts from beginning
i = 0;
//Read over file contents until either EOF is reached or maximum characters is read and store in character array
while( (fgets(&text[i++],sizeof(char)+1,fp) != NULL) && (i<MAX_CHAR_FOR_FILE_OPERATION) ) ;
//Ensure array read starts from beginning
fclose(fp);
getche();
return 0;
}
The easiest solution I can think of is to create an automata. That could be an enum with steps, for exemple:
enum AUTOMATE
{
FirstFloat = 0,
FirstSign,
SecondFloat,
EqualSign,
Answer
};
More info on how to use enum here : http://msdn.microsoft.com/en-us/library/whbyts4t.aspx
If you already have all each char in an array, iterate over the entire array using whichever loop you want, and check the integer value of each char. Use this table http://www.asciitable.com/ to check weather the integer value represents a number or a sign (-, +, =, etc). When each step is passed, tell your automate to go further (+=1). If you reach the end, you verified it. If not, then format is wrong.
It is not 100% clear what you want to do here.
If all you want to do is check that the expression is syntactically correct, that's one thing. If you want to check that it is also arithmetically correct (i.e. that the result on the RHS of the = is actually the result of the arithmetic expression on the LHS), that's another.
In either case, you must parse the input lines. There are several ways of doing this. The canonical, general, and robust way is to tokenize the lines with a lexer and pass the tokens from the lexer to a parser, which is a kind of finite state machine that “knows” the grammar of the language you are trying to parse (in this case infix arithmetic expressions). Given that you asked this question, it's reasonable to assume that you haven't got to this kind of material yet.
In your case, you are only dealing with simple infix arithmetic expressions of the form:
NUMBER OPERATOR NUMBER = NUMBER ;
You can get away with checking for lines that “look” exactly like this with one of the scanf() family of functions, but this is a fragile solution: if you add another term to the expression on the left, it will break; it takes considerable care to craft the correct format string; and it does not check for arithmetic correctness.
If all you need is something this simple, you can do it like this (I have omitted the file I/O):
#include <stdio.h>
#include <stdbool.h>
#define OPERATOR_CLASS "[-+/*]"
bool is_a_binary_infix_expression(const char *expr)
{
int count; // Count returned by sscanf()
float left_opd; // Left operand
char operator[2] = {'\0'}; // Operator
float right_opd; // Right operand
float result; // Result
char junk; // Trailing junk
// Format specifier for sscanf():
const char *format = "%f %1" OPERATOR_CLASS "%f =%f ; %c";
// Attempt conversion:
count = sscanf(expr, format, &left_opd, operator, &right_opd, &result, &junk);
// If exactly 4 conversions succeeded, the expression was good. If fewer,
// the conversion failed prematurely. If 5, there was trailing junk:
return count==4;
}
int main(void) {
int i;
int n_lines;
char *lines[]={
"1.5+2.2=3.7;",
"1.5 + 2.2 = 3.7 ; ",
"a+2.2=3.7;",
"1.5+2.2=3.7;x",
};
n_lines = (int)sizeof(lines)/sizeof(char *);
for(i=0; i<n_lines; i++) {
printf("'%s' is %s\n", lines[i], is_a_binary_infix_expression(lines[i]) ? "OK" : "NOT OK");
}
return 0;
}
This only checks for syntactic correctness. If you want to check for arithmetic correctness, you can switch on the operand to compute the correct result and compare that with the result extracted from the input line, but be careful not to fall into the trap of doing a direct comparison with ==.
I wrote the following program :
int main(){
char str[500],c;
FILE *f1=fopen("input.txt","r");
FILE *f2=fopen("output.txt","w");
while(c=fgetc(f1)!=EOF)
fputc(toupper(c),f2);
fclose(f1);
}
I was not getting the desired result though.
I rewrote the code using a do while loop.
int main(){
char str[500];
FILE *f1=fopen("input.txt","r");
FILE *f2=fopen("output.txt","w");
char c;
do
{
fputc(toupper(c),f2);
c=fgetc(f1);
}while(c!=EOF);
}
I figured out that the reason the first code fails is because in the while loop
while(c=fgetc(f1)!=EOF), we cannot guarantee that the left part of != is evaluated first and hence the results are not proper. Is this correct the explanation?
Yes you are correct; in your first code your while loop is written wrongly:
while(c=fgetc(f1)!=EOF)
Should be:
while((c=fgetc(f1))!=EOF)
// ^ ^ added parenthesis
Because the precedence of operator != is greater than = operator in conditional expression c=fgetc(f1)!=EOF, the first returned the result of comparing the value from fgetc() with EOF (either 0 or 1) and assigned that to c. (That means simply c=fgetc(f1)!=EOF expression is equivalent to c=(fgetc(f1)!=EOF) and this is not what you need.)
You need () to overwrite precedence as I suggested.
But you have second thing to improve that is c variable must be an int (not char) in order to hold an EOF-value.
A very good Read: Definition of EOF and how to use it effectively
I will add a little why c should be int, not char. Suppose you write
#include <stdio.h>
#include <ctype.h>
#include <locale.h>
int main(){
setlocale(LC_ALL,"");
FILE *f1=fopen("input.txt","r");
FILE *f2=fopen("output.txt","w");
char c;
while(EOF != (c=fgetc(f1))){
if(isalpha(c)) c = toupper(c);
fputc(c,f2);
}
return 0;
}
And your input.txt is
some text
Некоторый текст
Ъ - on this letter program will stop
in KOI8-R symbol Ъ have code 255 == -1 (when you use char).
That's why in case of using char instead of int will give your output.txt with only that text:
SOME TEXT
НЕКОТОРЫЙ ТЕКСТ
As for non-working code with parentheses: c=fgetc(f1)!=EOF could be denote by compiler as c = (fgetc(f1)!=EOF), that's why it's better always to add parentheses.
I recommend you to use flags -Wall -Werror when compiling your applications. In that case "forgetting" of parentheses would give you an error:
11.c: In function 'main':
11.c:9:2: error: suggest parentheses around assignment used as truth value [-Werror=parentheses]
cc1: all warnings being treated as errors
#include < stdio.h >
#include < string.h >
int main()
{
unsigned char a;
FILE *P;
P=fopen("mola.txt","r");
while((a=getc(P))!=EOF)
printf("%c",a);
}
Whats wrong with these code? When I compile it gives warning "comparison is always true due to limited range of data type." What does that warning mean?
You are storing the result of getc in a char. It should be an int. There's also a C FAQ on it. Also you should check the return value of the fopen.
P=fopen("mola.txt","r");
if (NULL == P) {
perror("fopen"):
}
Also the while looks fishy. Try indenting ?
while((a=getc(P)) != EOF)
printf("%c",a);
It means just what it says
comparison is always true due to limited range of data type.
The range of the data type in question (the a, which is unsigned char) is from 0 to 255 (really UCHAR_MAX);
The EOF value is -1
You are comparing a (from 0 to 255) with -1
(a != -1)
the condition will always be true
Try:
#include <stdio.h>
#include <string.h>
int main()
{
int a;
FILE *P;
P=fopen("tryit2.c","r");
while(EOF != (a = fgetc(P))) {
printf("%c",a);
}
}
You had two problems "getc()" returns an integer not a character. And the while statement had some weird side effects in the original order.
It means the loop will fell into Infinite loop not allowing the program to exit when at a=getc(p).