OK so basically I'm trying to get a program that transforms a hexadecimal that i enter into its equivalent base 10 value, i'm pretty sure the algorithm is correct, i just cant get it to correctly read what i enter, any help is much appreciated :) And I'm sorry to anyone who thinks this is a really stupid question.
int main()
{
char hexalpha[] = "aAbBcCdDeEfF";
int i, c;
int answer = 0;
c = getchar();
for (i= 0; answer == 0 && hexalpha[i] != "\0"; ++i)
{
if(hexalpha[i]== c)
answer = (10 + (i/2));
}
return answer;
}
You can't compare strings with != , and hexalpha[i] is a char. So you'd want hexalpha[i] != '\0' instead of hexalpha[i] != "\0"
Returning the answer from main() is a bit clumsy, printing out the answer would be easier, so do
printf("Answer: %d\n", answer);
return 0;
You are returning answer, not printing it. Your problem isn't input, it's output. Return passes the value to whatever function called it (or gives an exit status in the case of main).
At the beginning of your code, add the following:
#include <stdio.h>
At the end of main, replace return answer; with:
printf("%i\n", answer);
return 0;
Also, I'd recommend replacing "0" with '0' in the for loop. Your compiler will give you a warning because it should be a char, not a *char.
There doesn't seem anything wrong with your use of getchar. There is however a problem with the second half of your loop-condition: you compare an int (c) with a string ("\0"). You probably mean to use hexalpha[i] != '\0' (note the single-quotes).
Besides that, you don't see the answer because it's never printed. In most shells you can print the return-value of the last program with $? (on Windows it's %errorlevel%), like this:
echo $?
For example, if I run the program like this:
> a.out
b
> echo $?
11
You see that getchar works correctly, but you don't see the output because the shell doesn't usually print the return-value of a program. Alternatively, you can add a printf-statement at the end of your program. This is recommended anyway because the return-value of main is more commonly used to determine whether the program finished successfully, or not.
printf("%i\n", answer);
return 0;
}
Related
I know what the null-terminator in C is represented by \0 and has the numerical value of 0. However, when I execute the following code below, the program treats the null terminator as %. I searched this up online but I couldn't find anyone with this issue.
int main(){
char* forward = "hello";
int forward_length = 0;
while (*(forward++) != '\0') {
printf("%d\n", forward_length++);
}
if(*forward == '%'){
printf("Terminator Found");
}
}
The output is:
0
1
2
3
4
Terminator Found
Clearly, forward[5] does not equal the char %. Can someone please let me know what is wrong with the program?
The construction leaves forward advanced too far. This is because the post-increment will run even if the loop condition is false (as it is inside the loop condition). The obvious fixed loop is as follows:
for (;*forward != '\0'; ++forward)
printf("%d\n", forward_length++);
If you prefer to keep the while loop, --forward after the while loop will fix it.
An exercise asked to write a function that:
reads a sequence of alphabetic characters (without memorizing the sequence) that ends only when the users enters '\n'.
returns 1 if the number of capitalized letters went beyond the lower ones of at most an integer m, entered by the user, or 0 else.
I tried with the following code:
#include<stdio.h>
int read(int p,char c)
{
int M=0,m=0,d;
char A,Z,a,z;
while(c != '\n')
{
if(A<=c<=Z)
{
M++;
}
else if(a<=c<=z)
{
m++;
}
scanf("%c",&c);
}
if(M-m>0)
d=(m-M);
else
d=0;
if(d==0)
return 0;
else if (d<=p)
return 1;
}
int main()
{
int a,h;
char k;
scanf("%d", &h);
scanf("%c", &k);
a=read(h,k);
printf("%d\n",a);
return 0;
}
At this point, trying to execute the program with the gcc command, i noticed that the program was taking just the integer, let's say 2, and gave back 0 as if it entered in the function without taking the second scan on the character.
Besides the formal misconception and errors about the program and c function that i'm glad you rectify,
I was trying to understand, because as they say i'm trying to be self-taught, how scanf function and function work in general, when and to who priority is given.
For example in function read it's not clear to me when the value i'm returning to the function are taken putting a higher if as i did.
This isn't going to do what you probably expect
if(A<=c<=Z)
... for all sorts of reasons. Firstly, the values of A and Z are uninitialized. Second, the logic is written to be read by a mathematician, not a C compiler.
You almost certainly wanted this:
if('A'<=c && c<='Z')
... and remove the four variables char A,Z,a,z;
Note that use of character constants such as 'A' and 'Z' assumes a runtime environment using ASCII character sets. If you're interested in a more portable solution, you can look up isupper() and islower()
I'm trying to do an assignment for a class where we create a while loop using the scanf function. Basically the program is a calculator where the user should be able to type things like add 20 and my main function should be able to call up the functions from another .c then continue on in the loop.
However this is first time I am programming and I have no idea how to format or begin a loop that scans the input from the user, calls the appropriate mathematical function, applies it, then continues on in the loop.
Here's what I have done for the loop so far, which surprisingly, didn't work:
#include "calc.h"
#include "stdheader.h"
int main(int argc, char ** argv){
int c;
char token[81];
while(c != EOF){
if (scanf("%s", token) == "clear"){
calc.clear();
}else{
}
}
return 0;
}
and here is a sample of the functions that it should be able to call up (or what I have for them at least)
int local;
local = 0;
void clear(void){
local = 0;
printf("\n%d", local);
}
void add(int c){
local = local + c;
printf("\n%d", local);
}
In C, strings (and arrays more generally) are not first-class data types and cannot be compared by ==. Moreover scanf() does not return a string in any case - you should read the documentation carefully.
Change:
if (scanf("%s", token) == "clear")
to:
scanf( "%s", token ) ;
if( strcmp( token, "clear" )
Additionally the test c == EOF is dangerous because c is not initialised.
int c = 0 ;
My observation:
comparing string with == is not a suggested one. Instead try to use strcmp
scanf() returns only integer, you are comparing it to clear in if (scanf("%s", token) == "clear")
changing code like
if(scanf("%5s", token) == 1 && strcmp("clear",token) == 0)
Also what is the initial value of int c = ? without this how can you compare here while(c != EOF)
You need to look at the details of how scanf() works.
Here is a good reference.
scanf() returns the number of tokens read, an int not a string. You can't compare strings with == anyway. To compare strings you would have to use strcmp() from the string.h library.
You don't need to prepend calc on the front of your clear() function.
There are several errors here, you're best path forward might be to try something simpler first.
However this is my first time programming and I have no idea how to format or begin a loop that scans the input from the user, calls the appropriate mathematical function, applies it, then continues on in the loop.
When you want to solve a problem that is more complex than you think that you can solve it break it up in sub-problems. First design the user interface. What should the user enter to communicate with the program.
When you have a plan integrate the features that you need:
parsing user input
formatting of output
number processing (some arithmetic in your example).
A completely different approach to solve your problem.
Have array of function pointers.
typedef int (*func) (int,int);
func a[] = {add,sub,div,mul};
Have your UI like
printf("0 - add , 1- sub, 2 - div, 3 - mul\n");
scanf("%d",&op);
printf("Enter 2 numbers\n");
scanf("%d %d",&var1,&var2);
Now have
a[op](var1,var2);
Define your functions accordingly . For eg
int add(int x,int y)
{
return x+y ;
}
and so on.
program
int main()
{
int a=0xabcd;
char *p=&a;
while(p)
{
if(*p=='c')
{
printf("i got %c\n",*p);
return;
}
p++;
}
}
1)why i got always an answer like "i got c".
2)no matter how many times i execute this program, why i got %c as c.
3)replace c character with any character, no matter ,why we got such a character that what we put in if condition?.
if(*p=='z') or if(*p=='t') or ....
4)can anybody explain what was the reason?
int a=0xabcd on a 32 bit machine will give you 0x0000abcd. If you try to read the contents of this integer as a character, you'll either get 0x00 or 0xcd, depending on endianess. Neither is a printable ASCII character. This doesn't make any sense.
while(p) means "while p points at an address which is not zero". This doesn't make any sense. Because of this, you continue to loop and read random memory cells outside the allocated integer. Anything can happen. If you are lucky, the program will crash.
To sum it up, it appears you don't quite know what you are doing...
1) You get i got c because your program has a pointer p that points on each bytes of 0xabcd in sequence and beyond ! At some point, the pointer will point on the byte 0x63 which is 'c'. Since this is the if condition, the print statement prints the char pointed by p and you see the message i got c.
2) because of the if condition that execute the print statement only if the byte pointed by p is 0x63 thus 'c'. This is why you always see the same message. Note however that it only works if there is a byte with value 0x63 somewhere in memory.
3) You would write it like this to display other characters.
if((*p=='z') || (*p=='t') || ....)
4) see above answers.
Apart from the nice answer by Mr. #Lundin, just to clarify the logic for the print s,
1)why i got always an answer like "i got c".
Because, you wrote the code to do so. Keeping away the programmatic errors, if you check the logic, you wrote the code so that the printf() will only be executed if *p has a value equal to c. So, no wonder, all the time printf() (if encountered) will print
i got c
Next,
2) no matter how many times i execute this program, why i got %c as c.
Correct. Same reason as above.
3)replace c character with any character, no matter ,why we got such a character that what we put in if condition?.
Your printf() will only be executed if the if condition satisfies. So whatever character you'll use in your if condition, printf() will print only that character only.
You don't seem to know what you're doing.
Closest working exaple would look like this:
#include <stdio.h>
int main()
{
int a[2] = {0x0a0b0c0d, 0};
char *p = (char *) a;
while (*p)
{
if (*p == 0x0c)
{
printf("i got c\n");
return 0;
}
p++;
}
}
Or another better solution:
#include <stdio.h>
int main()
{
int a = 0x0a0b0c0d;
for (int i = 0; i < sizeof (int); i++)
{
if(((char *) &a)[i] == 0x0c)
{
printf("i got c\n");
return 0;
}
}
}
I have seen similar questions but none of them have helped me. I am wanting to check if user input is equal to "q" and if it is then quit from the program but 0 is never returned.
I have seen that the string needs to be terminated with a NULL (\0) value but I don't know how I could do this in the way I am working. I have the following:
char *input = "\0";
linelen = getline(&input,&len,stdin);
if(strcmp(input, "q")==0)
{
return;
}
My problem is that I really want to be using getline if possible because it works quite well for what I need to do and if I change input to char *input[2] I can't use getline without causing problems.
(When I type q into the program it returns 10. Also, I am quite new with C so sorry for any stupid mistakes.)
EDIT: I got the result of 10 when doing the following:
int j = strcmp(input, "q");
printf("%d", j);
INPUT:
q
OUTPUT:
10
getline reads a line from the input INCLUDING THE NEWLINE ON THE END OF THE LINE. So your input of q is actually the string "q\n", which is not the same as "q" and so compares as different.