I am using ubuntu 12.04 lts with gcc. This ANSI C code has no error or warning when it is compiled, but when i try to execute a.out file, some junk values appear.
Can anyone tell me, what is wrong with this program?
#include <stdio.h>
int get_int(void);
int main (void)
{
int ret;
ret = get_int ;
putchar(ret);
printf("\n");
return 0 ;
}
int get_int(void)
{
int input;
char ch;
while ((scanf("%d", &input)) != 1)
{
while ((ch = getchar()) != '\n')
putchar(ch);
printf(" is not an integer.\nPlease enter an ");
printf("integer value, such as 25, -178, or 3: ");
}
return input;
}
You're missing parentheses in your function call. This:
ret = get_int ;
should be:
ret = get_int();
Also, both getchar() and putchar() deal in int, not char.
If your compiler isn't warning you about these things, particularly the first one, then either you need a new one, or you need to turn the warning levels on it up.
Also, as Gangadhar points out, right now you're reading in an integer and printing it out as a character, so entering 68 will output D, for instance, on a system that uses ASCII. This may be, but probably isn't, the behavior you want, so replace your putchar() with a call to printf() if it isn't.
These Below two statements are not correct
ret = get_int ;
putchar(ret);
correct them as below
ret = get_int () ;
printf("%d\n", ret);
in the above ret =get_int ; this says compiler to store the pointer into an integer(the function name it self points to function) And at that place you need to make call to function.here your function did not take require any arguments so your call should have Empty parenthesis preceded by function name. and the second one is you are using putchar function to print integer value.you need to use printf with %d specifier.
Related
I have a problem with scanf() and printf() function in a snippet of code like this:
#include <stdio.h>
int main() {
int a;
int b;
int c;
scanf("%d %d", &a, &b);
while (c >= 2) {
c = a % b;
a = b;
b = c;
printf ("%d\n", c);
}
return 0;
}
What I expect to happen, and happens in my brother's Code::Block, is for the program to wait for input from stdin and then print to stdout the results, one per line, until it reaches the highest common divisor.
However, when I type it in vi and then compile it with gcc and run the program from my terminal, the program correctly takes the input but exit without returning anything to stdout.
If I comment out the scanf() line and hardcode any number to a and b variables, everything works as expected.
I'm trying to learn C and I've read basic documentation on the functions, but I can't help to understand this kind of behaviour.
I've tried to put a setbuf(stdout, NULL) before declaring variables but nothing changed.
Can somebody give me a clue?
There's nothing wrong with your scanf and printf calls but, as others have mentioned, one obvious problem is that you are testing the value of an uninitialised variable (c).
Maybe, what you want is a do { ... } while (...); loop, rather than a simple while loop.
The following code will guarantee to execute the loop at least once and then, at the end of each loop, check whether or not to repeat it:
#include <stdio.h>
int main() {
int a;
int b;
int c;
scanf ("%d %d", &a, &b);
do {
c = a % b;
a = b;
b = c;
printf ("%d\n", c);
} while (c >= 2);
return 0;
}
(Alternatively, initialise c with a value that is >= 2, i.e. use the declaration: int c = 3;.)
For further discussion of the do .. while loop, see here: 'do...while' vs. 'while'
I'm trying to create a simple converter that will ask a user to input data n times. The scanf() in the loop ideally should allow user to input a response in the terminal, press enter, then pass an output, then ask again....n times. But the program so far, just asks one time and never allows user to ask again.
There are many posts about scanf in loops I've seen, but I wasn't able to connect my issue with any of them.
I'm new to C, coming from Java.
#include <stdio.h>
double feet(double m);
double lbs(double g);
double f(double c);
//double askInput(int num);
int main()
{
int num, i;
i = 0;
printf("how many?\n");
scanf("%i\n", &num);
for(i = 0; i < num; i++)
{
double input = 0.0;
double output;
char unit = NULL;
printf("num to convert, units to convert?\n");
//scanf("%lf %c\n", &input, unit);
if(input == 0.0 && unit == NULL)
{
//input = askInput(num);
scanf("%lf %c\n", &input, unit);
}
//meters to feet
if(unit == 'm')
{
output = feet(input);
}
}
I've tried a number of things. I've tried using a while loop, I've tried putting scanf in a separate function and then also using if statements. I imagine I am not quite understanding how scanf works.
You have a couple issues here.
You're assigning NULL (of type void*) into a char as well as comparing these values later. Don't do this. If you want to use some sort of canary value you could instead use the character '\0' (or any other non-readily enter-able character).
You've given scanf a parameter that it expects to be a char* as a char. In order for the line scanf("%lf %c\n", &input, unit); to work as intended, you should have an ampersand in front of unit in order to pass a pointer to the local variable unit.
Giving scanf trailing whitespace requires it to read all subsequent whitespace until it can determine a block of whitespace has ended (see man 3 scanf for some more info, but note that any whitespace character in the format string is treated equivalently). In this instance having a newline on the end of your scanf calls will require them to read some amount of whitespace and then a non-whitespace character (see also the accepted answer here: white space in format string of scanf()). Just leave off the \n.
Some of your braces (namely the block for the function main) aren't closed. I'm assuming this is just a function of copying-and-pasting into SO though.
Most of this could be avoided with a stricter compilation command. If you're using gcc with the C99 standard you could try
gcc -Wall -Werror -Wextra -Wshadow -pedantic -std=c99 source_file.c.
First of all, I recommend using the _s functions instead of the regulars (for example printf_s and not printf). Second, I wrote down a version of the code that is working. I noticed that whenever I added some text to scanf_s (for example a \n) the program didn't stop but when I printed it with printf the program stopped.
FYI: For initialization, you need to put a number that the user won't enter - If the user doesn't put a value num won't store 0 but -9.2559631349317831e+61. And you should use || instead of && because you want that num and unit will store a value! :)
Here's my code:
#include <stdio.h>
#include <string.h>
int main()
{
int amount;
printf_s("How many numbers would you like to recive?\n");
scanf_s("%i", &amount);
for (int i = 0; i < amount; ++i)
{
// Initialization of all variables.
double convertedNum;
double rawNum;
char unit[3] = "";
// Getting the variables.
printf_s("Please enter the number that you\'d like to convert and the unit to
convert to.\n");
printf_s("Number: ");
scanf_s("%lf", &rawNum);
printf_s("Units (m/ft): ");
scanf_s("%s", &unit, 3);
// To make sure that we're getting right input & the wanted amount of
// numbers.
if (rawNum == -9.2559631349317831e+61 || unit == "")
{
printf_s("Please enter a number and a unit!");
--i;
}
else if (strcmp(unit, "m") == 0)
{
convertedNum = rawNum * 3.2808399;
printf_s("\n\nAfter convention, the number is %f\n", convertedNum);
}
else if (strcmp(unit, "ft") == 0)
{
convertedNum = rawNum / 3.2808399;
printf_s("\n\nAfter convention, the number is %f\n", convertedNum);
}
}
return 0;
}
I'm writing a very simple C program for a basic course, and I have been getting EXC_BAD_ACCESS on line 14. I can't see what the problem is.
The program asks the user for a number, and then displays the ASCII character associated with it.
This only happens, AFAIK, when debugging my program with lldb. It works perfectly fine when running from the command line, or on onlinegdb.com.
Also, if I comment out line 13, and assign true or false to loop_ctrl, instead of the return value of UserWantsToExit, everything works as expected.
#include <stdio.h>
#include <stdbool.h>
void GetAndDisplayInput(void);
bool UserWantsToExit(void);
int main()
{
bool loop_ctrl = true;
while (loop_ctrl)
{
GetAndDisplayInput();
loop_ctrl = !UserWantsToExit(); /* EXC_BAD_ACCESS */
}
return 0;
}
void GetAndDisplayInput()
{
char input_char = '0';
printf("\nInput a number: ");
scanf("%i", &input_char);
getc(stdin); /* Gets rid of '\n' */
printf("\n\nIt's character '%c'!\n\n", input_char);
}
bool UserWantsToExit()
{
char choice = '0';
bool value = false;
printf("\nDo you want to exit? (Y/N): ");
scanf("%c", &choice);
getc(stdin); /* Gets rid of '\n' */
value = (choice == 'y' || choice == 'Y');
return value;
}
The format descriptor %i used in the call to scanf() in function GetAdnDisplayInput() requires a corresponding argument of type pointer to int. You are passing a pointer to char. Undefined behavior is undefined.
Note that your C compiler should have warned you about the mismatch between the format descriptor and the corresponding argument; you should make a habit of compiling with all possible warnings turned on.
I started learning C programming and in this program I am trying to get user input and then a line at a time and decide if it contains non-int characters. I've been trying this method:
scanf("%d", &n);
if (isalpha(n))
{
i = -1;
}
I googled a bit and learned the function isalpha is good way to do it. However, I'm getting a segmentation fault every time I test the fragment above with non-int characters (letters for example). Any suggestion would be appreciated.
The %d format specifier forces scanf() to only accept strings of digits. Given anything else, it will fail and leave n unfilled (and assuming you didn't initialize n before, it will be filled with garbage).
The crux of the problem is that isalpha() expects a value between 0 and 255, and has an assertion to enforce it. At least on my VC++ compiler, it causes a crash with an access violation when given an invalid value (in non-debug mode).
To solve this you just have to switch to a %c format specifier. Converting n to a char would also be advisable as that makes your intent of reading a single character clearer.
EDIT: Given your clarifications in the comments, you can leave everything as is and simply check the return value of scanf() instead of going the isalpha() route. It returns the number of values read successfully, so when it encounters a non-integer or end of file, it will return 0. E.g.:
int main() {
int n;
while (scanf("%d", &n)) {
printf("Got int: %d\n", n);
}
}
I have no idea why you're getting a seg-fault. I'd have to see more of your program.
But using "%d" for scanf will only accept integer values and you'll get "0" for n that isn't an integer and therefore isalpha(n) will always be false and i will never be set to -1.
Perhaps you aren't initializing i and therefore it is never set. If you are referencing it later, that's probably the source of your seg-fault.
Use scanf("%c", &n), like this:
int main(char** argc, int argv) {
char n = 0;
int i = 0;
scanf("%c", &n);
if (isalpha(n)) {
i = -1;
}
printf("you typed %c, i=%d", n, i);
}
Make sure you have a character buffer to store the value in. Scan it as a string, and then use isalpha():
char buffer[32];
sscanf("%32s", buffer);
// loop and check characters...
if(isalpha(buffer[i])) ....
Note the use of %32s, this is to prevent buffer overflows (32 == size of buffer)
Given that n is an integer, we can diagnose that you are reading a value into n which is not in the range 0..255 plus EOF (normally -1), so that the code for isalpha(n) is doing something like:
(_magic_array[n]&WEIRD_BITMASK)
and the value of n is causing it to access memory out of control, hence the segmentation fault.
Since scanf():
Returns the number of successful conversions, and
Stops when there is a non-integer character (not a digit or white space or sign) in the input stream,
you can use:
#include <stdio.h>
int main(void)
{
char n = 0;
while (scanf("%c", &n) == 1)
printf("you typed %d\n", n);
return 0;
}
When I compile the C codes (from Teach yourself C, 2nd edition-Herbert Schildt) written below in Borland C++ v5.02, I get a warning message as below:
"c61.c(7,6): Conversion may lose significant digits"
What's wrong?
#include "stdio.h"
main()
{
char ch;
ch = getchar();
printf(" You typed: %c", ch);
return 0;
}
Same problem with another example:
#include "conio.h"
#include "stdio.h"
main()
{
char ch;
printf("Enter a character: ");
ch = getche();
printf("\nIts ASCII code is %d", ch);
return 0;
}
getchar() returns an int, so that it can return non-character values like EOF. So when you store the return value in a smaller datatype, like a char, you are potentially losing information.
Schildt's books are commonly considered the worst available for learning C (or C++) and this is a good example of why. You would be well advised to get a better book, such as K&R.
The prototype for getchar is:
int getchar (void);
It returns an int because it needs to return EOF which is not a character.
Expanding on that, the function needs to be able to return any valid character, as well as being able to return a special "character" indicating that you're reached the end of file (or an error has occurred).
Since a char data type can only hold one of the characters, there would be no way to indicate this end of file if all the function returned was a char. That's because, if you selected one of those char values to represent end of file, you would not be able to tell the difference between the end of file and the actual character.
For example, let's choose 'A' to indicate end of file. When you actually get back an 'A' from getchar(), how will you know whether you've reached the end of file or whether the user actually entered 'A'?
To get around this, many functions that give you back a char will actually give you an int and use one of the integer values which don't have an actual char equivalent (such as -1).
In that case (assuming an 8-bit char), you would get back either a -1 if you've reached the end of the file or a value from 0 through 255 inclusive representing the character entered.
And you need to get yourself both a more modern book and a more modern compiler:
#include <stdio.h>
int main (void) {
int ch = getchar();
if (ch != EOF)
printf("You typed: %c\n", ch);
return 0;
}
Why anyone is still using Borland is this day and age (where gcc is both just as cheap and much better) is beyond me.
What about this alternative program? It works fine.
#include <stdio.h>
main()
{
char ch;
getchar();
printf("Enter the character: ");
scanf("%c", &ch);
printf(" You typed: %c\n", ch);
return 0;
}
Please leave some comments.