I am making a simple program to add two numbers. I've done everything correct but somehow it's showing an error.
I am using TurboC for windows7 64bit (downloaded from filezilla)... I've also used devcpp but but there its showing error in using void main()... Why this is so? Why it is not working?
Also, can anybody suggest some good software for programming console-based for projects C, C++, etc.?
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int num1=0,num2=0;
//printing hello world
//printf("Hello World!");
printf("Enter number 1 : ");
scanf("%d",num1);
printf("Enter number 2 : ");
scanf("%d",num2);
int num3 = num1+num2;
printf("The sum of %d and %d is %d",num1,num2,num3);
getch();
}
The problem is with your scanf(). When accepting values, you must add the & before the variable. The unary & returns the address of the variable next to it, and scanf() then stores the value at that address. But note that you do not need to use & in printf() unless you actually want to print the address. In short, change your scanf() 's to
scanf("%d",&num1);
and
scanf("%d",&num2);
Here's your working code code
#include<stdio.h>
int main()
{
int num1=0,num2=0;
//printing hello world
//printf("Hello World!");
printf("Enter number 1 : ");
scanf("%d",&num1); // see here
printf("Enter number 2 : ");
scanf("%d",&num2); // and here
int num3 = num1+num2;
printf("The sum of %d and %d is %d",num1,num2,num3);
}
The error with void main() is that it is no longer accepted. On older versions like TurboC, you can use void main(), but the standard clearly states that we should not use void for main(), instead you should use int main().
Read this for reference
What should main() return in C and C++?
And, don't use <conio.h>. It's not supported in the standard. If you want to clear the screen, add the header file <stdlib.h> and use system("cls");
Regarding a replacement for getch(), you can just use getchar(). ( although in some programs, you will have to use two or more getchar()'s )
There's one thing you should know, and that is that both TurboC and DevC++ are outdated.
You should probably get Code Blocks.
You get the "Declaration not allowed here" error because prior to C99 ( your IDE TurboC runs on an older version than C99 ) , variables had to be declared at the beginning of a block. You can use Declaration not allowed here error in C as reference
I'm only focusing on the error:
printf("Enter number 1 : ");
scanf("%d",&num1); //use & for input
printf("Enter number 2 : ");
scanf("%d",&num2); //use & for input
When you use scanf(), you must provide the address of the variable you write to using &.
scanf("%d",num1);
should become:
scanf("%d",&num1); //add the & to refer to the address
Related
First of all there is another question with the same title but the solutions offered there didn't work for me. Other question
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a, b, c;
fflush(stdout);//suggested solution in other question
scanf("%d%d%d", &a, &b, &c);
printf("Values entered: %d %d %d\n", a, b, c);
return 0;
}
The code works fine when I run it normally.
Output
1 2 3
Values entered: 1 2 3
But when I run in debug mode nothing is printed. When I hover over the variables they have these values.
a : 56
b : 6422420
c : 6422420
Another solution suggested was to put this code in the start of the main method.
int ch;
while ((ch = getchar()) != '\n' && ch != EOF); //suggested solution #1
Both solutions suggested in the post didn't work for me. I tried them both separately.
EDIT
OS : Windows 10
Compiler : MinGW
I would recommend to use spaces in your scanf format, and to test its return count, so:
a = b = c = 0; // better to clear variables, helpful for debugging at least
int cnt = 0;
if ((cnt=scanf(" %d %d %d", &a, &b, &c)) == 3) {
/// successful input
printf("Values entered: %d %d %d\n", a, b, c);
}
else {
/// failed input
printf("scanf failure cnt=%d error %s\n", cnt, strerror(errno));
}
fflush(NULL); // probably not needed, at least when stdout is a terminal
Read carefully the documentation of scanf (and of every library function) before using it.
BTW, Eclipse is just an IDE or glorified source code editor, your compiler could be GCC or Clang (and you probably can configure your IDE to pass appropriate options to your compiler). And scanf itself is implemented in your C standard library (above your operating system kernel).
But you really need to enable all warnings & debug info in your compiler (so compile with gcc -Wall -Wextra -g if using GCC) and to learn how to use your debugger gdb (breakpoints, step by step, variable querying, backtrace...)
You may want to use fflush and you should compile and run your program in a terminal (not under Eclipse, which is hiding a lot of useful things to you).
I am trying to run the following simple code to check if scanf() is working.
#include<stdio.h>
int main(){
int num=0;
scanf("%d",&num);//Scanf not working
printf("The number is %d",num);
return 0;
}
However, it gives me an output of zero even though I enter some value for the variable 'num'.
For further clarification, I just installed turbo c++ in my new laptop. Is this causing some problem?
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm trying to write and read from file. writing works fine, but when it tries to read, the program crashed. tell me whats the error?
The objective of this program is to store the record of students in a file.
Calculate the percentage, and find the highest and lowest percentage of student.
#include <stdio.h>
#include <conio.h>
#include <string.h>
struct result
{
char name[15];
int batchNo;
int rgtNo;
int marks;
float perc;
};
int main()
{
char answer, i = 1;
FILE *ptr, *abc;
result s, st;
int j;
ptr = fopen("rec.txt","a");
abc = fopen("rec.txt","r");
if(!ptr)
printf("Error opening file");
else if(!abc)
printf("Error opening read file");
else {
do
{
int sum = 0;
printf("\nEnter name of student %d: ", i);
scanf("%s", s.name);
printf("\nEnter Batch #: ");
scanf("%d", &s.batchNo);
printf("\nEnter Registeration no: ");
fflush(stdin);
scanf("%d", &s.rgtNo);
printf("\nEnter marks of Five subjects: ");
scanf("%d",&s.marks);
/*for(j = 0; j < 5; j++)
{
scanf("%d",&s.marks[j]);
sum += s.marks[j];
}*/
s.perc = sum / 5.0;
printf("Percentage of student %d: %f", i+1, s.perc);
fprintf(ptr, "%s %d %d %d %f", s.name, s.batchNo, s.rgtNo, s.marks, s.perc);
printf("\n\n\n");
printf("Do you want to add another record? (y/n) ");
answer = getche();
i++;
} while(answer == 'y');
printf("outside loop\n");
fclose(ptr);
fflush(stdin);
rewind(abc);
do
{
fscanf(abc, "%s%d%d%d%f", s.name, s.batchNo, s.rgtNo, s.marks, s.perc);
printf("in loop");
} while( !feof(abc));
fclose(abc);
}
}
So many defects, so little time.
C is not C++
They are two different languages. Remove the C++ tag.
But since you tagged it as C++, you should use the fstream and iostream libraries as well as the std::string type.
One pointer per physical file
You have one FILE * for each different mode of the same file. In many cases, this will confuse the operating system and heck some won't allow it.
Instead, use one FILE * and open the file as rw+ for read, write and append.
See fseek function.
Buffer overflow with scanf
You have reserved 15 letters for the name. What happens if the user types in a name longer than 15 letters? Buffer overflow. You could write over other variables that follow the name member.
You could resolve this by using fscanf with the C language or std::cin and std::string with the C++ language.
Flushing the input
The flush function only works with output buffers. Don't use with input streams.
In the C language you have to read characters until the buffer is empty or until your terminator character is found (such as 'n').
In C++ this is accomplished by cin.ignore(1000000, '\n').
Checking input functions for errors
You can't trust the User. You must check the scanf return value for errors. If you ask for a number and the User types in a number, the scanf will fail. The value is undefined.
the program crashes whenever you type something different than 'y' at the last question Do you want to add another record? (y/n).
think what happens after this stage in your program...
hint - take a look at your ptr and abc File pointers - do they point to the same file?
The issue which makes your program segfault is the fscanf call: you're supposed to pass pointers to variables for arguments. I guess you quickly C&P without double checking your code.
As mentioned in another answer: fflush behaviour isn't specified for input streams, though many implementations behave as you expect. Another way to flush is to do a loop on the stream and read char by char:
void flush_stdin(){
char c;
while (c != '\n' && c != EOF)
c = getchar();
}
Note: I'm using getchar, as getche isn't available on my system. I suppose you should have it too, and would recommend using it for portability.
Regarding multiple opening of the same file in different modes: I don't think it should be a problem, though it seems much more straightforward to open it in append mode first, close it when the input session is done, and then reopen it for reading afterwards. In a more complex program, you'd probably split these two functionalities in separate functions, each doing its own I/O, thus following that pattern.
One last thing: you probably want to test the result of your calls to scanf and the like. Perhaps a small macro like the following would help:
#define CHECK_SCAN(x) do { \
int err = (x); \
if (err <= 0) { \
printf("error on scan: %s", strerror(err)); \
exit(1); \
} } while(0)
I am using Microsoft Visual Studio 2012 Professional. I have a simple CPP code:
#include "stdio.h"
int main () {
int a = 0, b = 0, c = 0;
printf("\nEnter two numbers:\n");
scanf("%d %d", &a, &b);
c = a+b;
printf("\nc = %d", c);
return 0;
}
The problem I am facing is that the first printf statement is getting printed but the second one is not. The code is exiting without printing anything. However when I debug using breakpoints, the value of c is getting stored in it.
I'll take a wild guess and say you run this from your IDE.
It does print the output. But the program then ends. And it ends so fast, you cannot see the output. If you want your program to wait for you to see it, you will need to find a way to make it wait. For example with another scanf line.
As there is no standard, environment agnostic way to say "Press any key to continue", have a look here for some alternatives.
Add \n to the end of the last printf. It is implementation-defined whether the last line of output to stdout actually gets flushed , if it doesn't end in a newline.
When you use
scanf("%d %d", &a, &b);
then you should give 2 inputs separated by space or enter
scanf("%d,%d", &a, &b);
then you should give 2 input separated by comma(,).
and at last use
printf("Press any key to continue.."); getche(); instead of return;
I'm an absolute beginner to programming and i'm just doing some exercises exercises for the beginning.
First of all, i'm using Visual C++ 2010 to compile C-Code. I just create a new project and choose an empty console application. After that, I create a ressource file named test.c and change in the file properties the elementype to C/C++ Compiler and compile as C++ Code, so that i can use #include <iostream> for the std::cin.get() command. Now the code:
#include <stdio.h>
#include <iostream>
int main()
{
int number1, number2;
int sum;
puts("Enter number 1 please:");
scanf_s("%d",&number1);
puts("Enter number 2 please:");
scanf_s("%d",&number2);
std::cin.get();
std::cin.get(); //(1)
sum = number1 + number2;
printf("The average is %f\n", sum/2);
return 0;
}
Now my problem ist that the "std::cin.get()" command is just ignored. Afer typing in the two numbers the program just stops and the console window closes.
Any idea where the problem is?
I have another question please.
Since my problem with holding the console open is solved (1), now my printf() gives me just zeros as output. I want to have a float number as output but no matter what i type in as number1 and number2 i always get "0.000000".
Since i'm still working on my little program to verify the input before it is accepted, i have another question please.
I want to use the following code just to check the input.
#include <stdio.h>
#include <iostream>
#include <ctype.h>
int main()
{
int number1, number2;
int sum;
puts("Enter number 1 please:");
scanf_s("%d",&number1);
if (isdigit(number1))
{
puts("Enter number 2 please:");
scanf_s("%d",&number2);
}
else
{
puts("Your input is not correct. Enter a number please.");
}
std::cin.get();
std::cin.get();
/*
sum = number1 + number2;
printf("The average is %f\n", sum/2); */
return 0;
}
Well it doensn't work. I type in a digit and my response is "Your input is not...". I have used the search and found the following: Check if User Inputs a Letter or Number in C. Unfortunately the suggestions doesn't help me.
It's not ignored. When you type your second number, then hit enter, it puts your number plus a newline character in the input stream. scanf removes the number, but leaves the newline character alone. When you call cin.get(), since there's a character in the stream, it doesn't wait for your input.
PigBen has already given you a good explanation of where you err. However, I have some additonla points to make about your program which won't fit into a comment:
You are mixing C and C++ input. Why? What's wrong with std::cin >> number1?
When you change number1 to double, you need to remember to change the formatting string in scanf(), too, while with IO streams the compiler will figure out everything for you. With streams and C++' strings, containers and other data structures, it's much harder to do something that compiles, but invokes the dreaded Undefined Behavior at run-time.
Also note that you do not check whether your inputting operations succeed. What happens if I invoke your program, and instead of passing it numbers, I enter non-digits? Never use input from users, files, or other externals sources unverified.
With IO streams, the input operator >> returns (a reference to) the stream, and you can use streams as if they were booleans, so you can do
if(std::cin >> number1)
// input succeeded
or
if( !(std::cin >> number2) ) // note the negation operator !
// input error
to check.
Streams enter a bad state internally after input/output errors. Any further IO operations will fail on a stream that had encountered an error. Therefore, if you want, you can delay input verification until all input operations are done:
std::cout << "Enter number 1 please:";
std::cin >> number1;
std::cout << "Enter number 2 please:";
std::cin >> number2;
if(!std::cin)
// input error
However, remember to always verify input before you first use it.
Note that I didn't check the output for errors. That's because it's hard to imagine something going wrong with output to the console. (And what would you do about it? Print an error message?) However, if you write into a file, remember to check output, too. It's easy for a file operation to go wrong.
In answer to your modified question it is because you are using ints for division. Change int sum to float sum and everything should be fine.
To answer your modified question: you're using the %f printf() format with an int, and that doesn't work. If you want to print out floating-point, you need to pass a double. You could print out (double)sum / 2 or even sum / 2.0, both of which yield doubles. (No, a float doesn't work the same for a variadic function like printf().) As it is, you're passing what is probably a four-byte type and telling printf() to treat it as an eight-byte type of different format, so it's no wonder you're not getting the expected results.
Alternately, you could switch to C++ iostreams, which save you the problem of matching types and knowing the default promotions. You'd still get an integer from sum/2, and that would drop any one-half, but it would be the right result.