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).
Related
I'm trying to run a simple C program in Eclipse and I am new to Eclipse.
When running the command I see output of the program for a very brief moment in the console, but instead for the program to wait for input, output disappears and and an empty console is shown instead. Is this a problem of the program or something related to the settings of the Eclipse IDE?
Edit: On the console menu there is a terminate button and when I pres it the output of the program shows but it doesn't wait for input and the program is terminated. Any help?
Image:
Here is the code
//The input is a series of numbers and the number X. Find
//how many times the number X is met in the series
#include<stdio.h>
int main(){
int m[20];
int n, X, cnt=0;
printf("Insert maximum length of the series (n<=20)\n");
scanf("n= %d",&n);
printf("Insert X the number you are looking for\n");
scanf("X= %d",&X);
while(n<1||n>20){
printf("Bad input, n should be between 1 and 20\n");
scanf("n= %d",&n);
}
for(int i = 0 ; i < 20 ; i++){
scanf(" %d", &m[i]);
if(m[i]==X)cnt++;
}
printf("X is found %d times\n", cnt);
return 0;
}
and here is the empty console:
Edit: I've tried rewriting the code using cout and cin but then the compiler in Eclipse complains on the line #include<iostream.h> saying that there is an unresolved inclusion. Sounds like a separate question to me.
The answer is here: click
Basically the output of the standard input output is buffered and setvbuf(stdout, NULL, _IONBF, 0); solves the problem.
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
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;
Ok so I am trying to learn C and I want my user to input a value so I am using scanf. I started off not having the flushes, because nothing was comming up until I typed in two values. Now that I have them though I get the same problem there still is no output until after I type in two numbers. Here is my code:
#include <stdio.h>
using namespace std;
int main()
{
int i1, i2, sums;
printf( "Enter first integer\n" );
fflush(stdout);
scanf( "%d", &i1 );
printf( "Enter second integer\n" );
fflush(stdout);
scanf( "%d", &i2 );
sums = i1 + i2;
printf( "Sum is %d\n", sums );
fflush(stdout);
return 0;
}
Any help would be greatly appreciated.
The following works fine for me:
#include <stdio.h>
int main() {
int i1, i2, sums;
printf( "Enter first integer\n" );
scanf( "%d", &i1 );
printf( "Enter second integer\n" );
scanf( "%d", &i2 );
sums = i1 + i2;
printf( "Sum is %d\n", sums );
return 0;
}
and gives:
Enter first integer
1
Enter second integer
6
Sum is 7
This is using Cygwin under XP. What platform and compiler are you using?
Update: One possibility is that, because you're running from within the Eclipse environment, it may be doing some weird stuff that interferes with the normal I/O rules.
I'm pretty certain that stdout, even if it's not line buffered like stderr, will autoflush if you attempt to read from stdin (at least in most environments I've used, which is a few).
Eclipse may be fiddling around with the way it attaches the console to the program's actual I/O. I would try to compile the code to a standalone executable and then run it outside the Eclipse environment. If it runs fine there, then it's probably the interaction between Eclipse and the program.
As I stated, your program works fine under XP with Cygwin, even without the flushes.
Further explanation is warranted. As Jerry Coffin rightly points out in a comment, the C standard (c1x, 2009/03/01 draft) states:
5.1.2.1 para 6: The input and output dynamics of interactive devices shall take place as specified in 7.19.3. The intent of these requirements is that unbuffered or line-buffered output appear as soon as possible, to ensure that prompting messages actually appear prior to a program waiting for input.
5.1.2.1 para 7: What constitutes an interactive device is implementation-defined.
7.9.13 para 3: When a stream is unbuffered, characters are intended to appear from the source or at the destination as soon as possible. Otherwise characters may be accumulated and transmitted to or from the host environment as a block. When a stream is fully buffered, characters are intended to be transmitted to or from the host environment as a block when a buffer is filled. When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered.
7.9.13 para 7: At program startup, three text streams are predefined and need not be opened explicitly - standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.
What may be happening is that the way Eclipse interacts with the programs input and output may be causing the program to not recognize stdout as an interactive device. It would then be fully buffered, meaning that you wouldn't see the output until the buffer is full, or the program terminates.
I think you need "\n" in side the "scanf". Like this.
scanf( "%d\n", &i2 );
Try it.
i think your are flushing out the wrong stuff , try flushing scanf using stdin not using stdout,just like this
#include
main()
{
int i, j,sums;
printf("enter the first integer\n");
scanf("%d",&i);
fflush(stdin);
printf("enter the second integer\n");
scanf("%d",&j);
fflush(stdin);
sums = i + j;
printf("sum is %d\n",sums);
//fflush(stdin);
getchar();
}