scan arithmetic operands c and compare them with string - c

I am trying to scanf arithmetical operands into variable. I want to put "+" into variable. I tried everything I have found but nothing has worked so far. The best thing I came with is:
char plus = "+";
char* c;
scanf("%c", &c);
if (strcmp(plus, c) == 0) {
printf("you have + in variable");
But this does not work. It seems like "+" does not get into variable plus nor does it get scanned into variable using scanf. Is there any trick for this?

There are multiple errors in there:
you declare a char plus and you initialize it with a char* (and not a char).
scanf with %c expects a char* but you are providing a char**
you are comparing a char with a char* in strcmp
If you are dealing with single character operators there's no need to do things more complex than they are:
char plus = '+';
char c;
scanf("%c",&c);
if(plus == c)
printf("you have + in variable");

Related

How on earth to use char and if statements?

I'm a rookie programmer trying to run a simple code on VS code.
#include<stdio.h>
int main()
{
char* a;
printf("Enter a char");
scanf("%s",&a);
if (a = "yes")
{
printf("Number is 30");
}
else if (a = "no")
{
printf("Number is 50");
}
else{
printf("oops");
}
return 0;
}
I guess looking at the code you guys can figure out what I'm trying to do, if the user enters "yes", a specific sentence need to be displayed and similarly for "no".
The problem here is whatever I write in the input, it will always print the first statement, "Number is 30". I've tried running similar codes but ended up with the same output.
If possible, please explain me how to use char,strings,arrays with if-else statements.
There are several misunderstandings in the posted code.
First there is a misunderstanding of char versus string. A char is for instance a single letter, a single special character like ., ;, etc. (see note1) while a string is a serie of chars. So
'y' is a char
"yes" is a string
You print "Enter a char" but from the code it's obvious that you really want "Enter a string".
This leads to the next problem. To input a string using scanf you need to pass a "pointer to char". Your code pass "a pointer to pointer to char" due to the &. Further the passed pointer must point to some memory. So you need:
char a[10]; // Make it an array of char so that it can hold a string
printf("Enter a string, max 9 characters");
scanf("%9s", a); // No & before a and width specifier used to avoid buffer overflow
Now this part
if (a = "yes")
is not the way to compare two strings in C. For that you need the function strcmp - like:
if (strcmp(a, "yes") == 0)
Putting it together it's like:
int main()
{
char a[10];
printf("Enter a string, max 9 characters");
scanf("%9s", a);
if (strcmp(a, "yes") == 0){
printf("Number is 30");
}
else if (strcmp(a, "no") == 0)
{
printf("Number is 50");
}
else
{
printf("oops");
}
return 0;
}
That said, I don't understand why you print stuff like: "Number is 30" but that's kind of irrelevant here.
note1: The type char is actually an integer type, i.e. a number, but the common use is to map these numbers to characters using ASCII encoding.
There are different ways to initialize a variable to access C string.
char *char_ptr = "Hello";
This initializes char_ptr to point to the first character of the read-only string "Look Here".A C string initialized through a character pointer cannot be modified. When a C string is initialized this way, trying to modify any character pointed to by char_ptr is undefined behaviour. An undefined behaviour means that when a compiler encounters anything that triggers undefined behaviour, it is allowed to do anything it seems appropriate.
A more convenient way to define strings that can be modified is to use:
char str[];
This way you can modify any character in the C string
p.s you also need to use strcmp() for the if statement
You can take string input in C using
scanf(ā€œ%sā€, str);
And to compare the string you need to use:
strcmp(str1, "yes");

comparing getchar with a character returns a warning and gives me the wrong code

i'm having a problem with comparisons using getchar() and file redirection.
I have a code that resembles this:
char result = getchar(); // getchar returns the next char in the file
int linecount = 0;
if (result == "\n") {
linecount++;
}
But I get a warning when compiling it. It says that I can't compare an int with a pointer, but from my understanding, result is a char and so is "\n", so I'm really confused. I can also use printf("%c", result") and it works fine, implying that result is a char. Does anyone know why I'm getting this error? Thanks! Also, running the code, linecount will always return 0 even if the first character in the file I'm using as my input is a newline.
You are comparing a char with a char *, that is, a string. "" (doublequoted) values are treated as strings in C, so your code should be
if (result == '\n') {
linecount++;
}
Alternatively, you could use strcmp or strncmp with the char casted to a pointer, but that's not necessary.
Do note that the size of a char is less than an int so the conversion from a char to int doesn't make you lose anything.

How to convert gchar* to char

When I press a key(integer) on my keyboard. It does something like:
gchar *keypressed;
keypressed=gdk_keyval_name (event->keyval);
printf("The KeyEvent is: %s\n", keypressed); // Till here it is fine
I get segmentation fault when I do this:
char ch;
sprintf(ch, "%s\n", keypressed);
printf("The NewKeyEvent is: %s\n",ch);
I need to convert it as I am going to use the value in a switch case. Without converting it is not possible.
gchar is a typedef alias of char, so the problem is not with the type conversion. You need to allocate some space for the sprintf buffer.
Currently, you are passing a single uninitialized char to where a pointer should be. You should get a warning from the compiler, in addition to a segfault caused by undefined behavior.
To fix this, make an array of chars and pass it to sprintf instead:
char ch[10];
sprintf(ch, "%8s\n", keypressed);
printf("The NewKeyEvent is: %s\n", c);
Note the limit of 8 in the sprintf. This is because ch is of size 10, and we need two extra spots for '\n' and '\0'.
If you want only a single character from the keypressed string there are two ways:
Use array indexing, this way you can access any character in the string:
char ch = keypressed[x]; // Where `x` is the character number you want
Remember that array indexing starts from zero, so the first character in the string is number 0.
If you want the first character, you can also use the dereference operator
char ch = *keypressed;
This equivalent to
char ch = keypressed[0];

Unknown Error with Conversion [C]

For some reason when building my program, it says that I have this error:
error: invalid conversion from 'char' to 'const char*' [-fpermissive]
strcpy(phrase[counter].word, ch);
I'm not really sure what the compiler means, I've tried changing char ch to const char ch, but that doesn't seem to fix the issue. If anyone could shed some light on this issue that would be great.
Here is the code you can refer to:
const char* clean_word(void);
void create_word(struct Word_setup phrase[], FILE *fp)
{
char ch;
fscanf(fp, "%s", &ch);
strcpy(phrase[counter].word, ch);
strcpy(phrase[counter].word, clean_word());
}
const char* clean_word()
{
int i;
const char *ch = phrase[counter].word;
ch = phrase[counter].word;
for (i = 0; i < M; i++)
{
if (phrase[counter].word[i] == 39 || isalpha(phrase[counter].word[i])) //39 is the ASCII value for: '
i = i; //Just to be there, no reason to it. I just want the program to do nothing if its a letter or '
else
phrase[counter].word[i] = '\0';
}
return ch;
}
Also in case you're wondering what this is for, I'm building a program that will scan a *.txt file and then print out the word with the highest number of appearances, as as well as the number of appearances.
If you've already read my old post, I decided to try writing it without re-allocating space every time the array gets filled, and I just set it to 200 max different types of words. I will change the program once I'm finished so that it reallocates space every time that the array fills up.
The problem is here:
char ch;
fscanf(fp, "%s", &ch);
strcpy(phrase[counter].word, ch);
The strcpy() function expects its second argument to be a pointer to the head of the source string, but ch is a char, not a char * or const char *. As Keith Thompson explained, this is an error because integers are not implicitly convertible to pointers in C (other than a constant expression with value 0). Even if the compiler performed an implicit conversion anyway, the behavior would surely not be what you want.
Moreover, the fscanf() isn't going to do what you want, either, because even though argument &ch is the correct type for the format string it accompanies, it is a pointer to only a single character of storage, and the fscanf will always write outside its bounds if it successfully scans a string (because it must write a string terminator even for a one-character string).
#BLUEPIXY's approach is much better, supposing that phrase[counter].word is a char array, but even there you risk overrunning its bounds. To protect yourself against that, specify a field width. For instance, if phrase[counter].word is an array of 20 chars, then use this ...
fscanf(fp, "%19s", phrase[counter].word);
... to ensure that scanf() does not write more than 20 chars (including a string terminator) to the array.
maybe...
void create_word(struct Word_setup phrase[], FILE *fp)
{
fscanf(fp, "%s", phrase[counter].word);
clean_word();
}

C -- Conditional always jumping to 'Else'?

I am working on learning C and am using some practice problems from the Python book I recently finished. My C book is in the mail, but I wanted to get a head start. I was putting together a simple temperature conversion program and for some reason it always jumps to the 'Else' clause in my conditional... I'm sure I'm missing something simple, but I can't seem to figure it out. Any ideas?:
#include<stdio.h>
main()
{
float temp_c, temp_f;
char convert_from[1];
printf("Convert from (c or f): ");
scanf("%c", &convert_from);
if(convert_from == "c")
{
printf("Enter temperature in Celsius: ");
scanf("%f", &temp_c);
temp_f=(1.8*temp_c)+32;
printf("The temperature in Fahreinheit is: %f \n", temp_f);
}
else if(convert_from == "f")
{
printf("Enter temperature in Fahreinheit: ");
scanf("%f", &temp_f);
temp_c=(temp_f/1.8)-32;
printf("The temperature in Celsius is: %f \n", temp_c);
}
else
printf("Invalid choice. \n");
}
If you are comparing characters do this:
char convert_from;
printf("Convert from (c or f): ");
scanf("%c", &convert_from);
if (convert_from == 'c')
{
Otherwise you can't perform the comparison with a string literal "c" (note the double quotes) like that.
In the expression:
if (convert_from == "c")
convert_from array is converted to a pointer to char, so you are basically comparing a pointer to char to another pointer to char. "c" is a string literal while 'c' is a char (note the use of "" in the first case and of '' in the second case).
With a char convert_from[1]; declaration, here would be the correct code:
char convert_from[1];
scanf("%c", convert_from);
if (convert_from[0] == 'c')
but it is more natural to directly use a char instead of an array 1 of char:
char convert_from;
scanf("%c", &convert_from);
if (convert_from == 'c')
Well two problems here.
First: You want only to read a single character, so declaring
char convert_from;
instead of an array of chars with size 1 (as char convert_from[1] did).
And secondly you need to actually compare to a single character, so you would need to do
if (convert_from == 'c') ...
instead of "c", because "foo" is a string in C which in turn is a pointer to a constant
character array (const char *).
Additionally: which compiler did you use? Mine (llvm-gcc 4.2) warned me about the issues. So either your compiler is quite bogus or you will urgently have to pay attention to compiler warnings. This might be difficult, as warnings are no errors, however, warnings are there for a reason :-)
In C, you cannot compare strings using == (what happens if you do is that the memory locations of the strings get compared, which will yield different results in most cases).
Also scanf("%c", &convert_from); is wrong. The array itself will already decay into a pointer, so scanf("%c", convert_form); will suffice. In this case however, convert_form will not contain something your C library will consider a string (strings are null-terminated in C). A minimally invasive change for getting your code to work would be changing
if (convert_from == "f") [...]
to
if (covert_form[0] == 'f') [...]
(mind the '' instead of the "", which is a character literal, which basically is just a number and can thus be compared using ==).
A more idiomatic way to do this would be to declare convert_form as char convert_form and then use scanf("%c", &convert_form);, which would accomplish the same as the above.
First of all since you are reading only one character at a time
define it as
char convert_from;
next it is not advisable to compare strings directly
hence the statement should be
if(convert_from == 'c')

Resources