C/C++ BEGINNER - fgets with stdin causing unexpected 'loop' results - c

I'm a programming student who's only really looked at Java up until now. This semester is our first time using C and I'm having a lot of trouble wrapping my head around some of the simplest functions. I really have no idea what I'm doing. I couldn't even get Eclipse to work correctly with MinGW so I eventually gave up and reverted to Netbeans.
So basically I'm trying to use fgets to read user input for a switch-case menu, but I can't get fgets to work in even the simplest situations. To troubleshoot I tried copying a simple fgets example from online, but even that is giving me unexpected results.
When I run the code below it just runs an infinite empty loop (it does not prompt for user entry at all, it does not accept any user entry, it just 'runs' forever and the console remains blank). When I delete the fgets line and remove the other reference to the 'name' variable it works as you would expect (prints the user entry prompt and then ends).
Example code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
char name[10];
printf("Who are you? ");
fgets(name,10,stdin);
printf("Glad to meet you, %s.\n",name);
return(0);
return (EXIT_SUCCESS);
}
Any advice would be appreciated!
Other info:
I am running - Win 8 (poor me) & Netbeans IDE 8.0 (with MinGW)
When creating my C project I select File=> New Project=> C/C++=> C/C++ Application
EDIT: When I run the program I have tried:
1) right clicking the project file => Run; and
2) clicking the big green arrow in the netbeans ribbon;
.... neither works.

This code should work, but for you to be able to input anything, you need to run in in a proper terminal.
My guess is that you're running it inside your IDE and it's set to use pipes as stdin/stdout. Instead you should start cmd.exe and run the program in there (you'll have to navigate to the correct directory first).
Or, optionally, there might be a setting in your IDE to run the program using cmd.exe or with a builtin terminal.
A final note. You should learn to use sizeof whenever a buffer size is required. I.e. change this:
fgets(name,10,stdin);
to
fgets(name, sizeof(name), stdin);
Also, please use spaces to make your code more readable. Reading code is a big part of programming.

1) You might want to flush the file, after printf("Who are you? "); with fflush(stdout);
2) You have two return statements (which is harmless).
Other than that, your code is fine.

It works perfect - but you might want using fflush(stdin); before the fgets() call.
Also remember fgets return a string with '\n' after a user input - solved simply with name[strlen(name)-1]='\0'; - which is basically putting NULL as an "end of a string" symbol, basically you remove the '\n'.
And DO NOT change 10 to sizeof(name) - it doesn't matter at all, basically it's even supposedly worse as you can't use this in functions properly (sizeof(name) won't always match the length and would be the size of the pointer).
You should try compiling with MinGW if it didn't work, it will surely work on it.
A reminder: fgets() may let you enter MILLION characters, but it will take the first 10, in this case, at least.

Related

Get highlighted text & open program with it (replicate clipboard.exe behavior)

Is it possible to highlight text with your cursor in any program, like you do with str+c and start a tool with the highlighted text as argument?
As far as I know, in Linux as well as in Windows, one can call a script/program with a custom shortcut. I assume str+c just does the same, calling a little program with the highlighted text as argument. How to replicate this?
For demonstration purposes, let's take this C - program printing the value it was called with:
#include <stdio.h>
int main(int argc, char**argv){
if(argc == 2){
printf("program called with: '%s'\n", argv[1]);
}
}
Can one type the text "HelloWorld" in Word for example, highlight it, and press something like str+alt+p, calling
someprogram.exe HelloWorld
or as for Linux
someprogram HelloWorld
I am really curious if this is possible.
Edit: I'm interested to know, how to replicate the clipboard.exe functionality. I have written a program "write_custom.exe" storing anything given as argument (argv[1]) in a text-file, after deleting it's previous content. Other programs can read the content of this text-file and so are able to use this custom clipboard. It's purpose is mainly for self-teaching.
As I am at the beginning of my codeing career, I only know C, but I am open for solutions in other languages as well. My goal is to run this write_custom.exe, with highlighted text as argument, on my computer and my Linux-VM.
You might want to check out ncurses (Linux) and Console API (Windows). The code will not be cross-platform, but you can pretty easily write some code to make them share some basic behavior :).

Code wont compile or throw an error when using scanf in C, gets stuck building forever

I want to preface this with the information that I am pretty inexperience with coding.
Whenever I try to compile my code, it never finishes building and never throws an error. I then have to use Task Manager to stop stuck.exe (stuck is the name of the c file) so that I can try to compile again. I have narrowed down the issue to having something to do with the scanf function.
#include <stdio.h>
int main(void) {
int number = 0;
printf("this line shouldn't break anything. number = %d\n", number);
printf("what should the new value of number be?: ");
scanf("%d", &number);
return 0;
}
When I remove the line that has the scanf function, the rest of the code compiles as it should.
I am doing all of this in SublimeText3 on Windows 10 and using GCC provided by MinGW.
Any information you can give to help me would be appreciated, and If you would like any more information please let me know.
If you have a process stuck.exe, it means that the program finished compiling and was automatically started by the IDE/text editor. scanf reads from standard input, but apparently the IDE does not execute it in an interactive fashion, so that you cannot enter the number via the IDE.
In your IDE, you need to use the Compile or Build command (and not Run), and invoke stuck.exe manually in a command shell window.
Even my compiler is GCC-MinGW and i use Vscode, And your program works just fine even with online compilers.Maybe there is a problem with your C installation or check if your system memory near to full it might cause problems like these sometimes.

Using C and trying to create a mad lib.

As my title says I'm a new programmer learning C. This is my second day programming and I need help fixing this problem in my code. I'm making a mad lib and while no errors come up the first scanf takes 2 lines rather than the 1 every other scanf uses.
Here's the code:
#include <stdio.h>
int main()
{
char verb[20];
char loc[20];
char noun1[20];
char noun2[20];
char adj[20];
/* The following is the part where you input words. It sets them as strings (named word1-5, as stated above)*/
printf("Welcome to Mad Libs! \nAnswers can only be one word long. \nPlease enter a verb.\n");
scanf("%s\n",verb);
printf("Now enter a location!\n");
scanf("%s\n",loc);
printf("Now enter a noun!\n");
scanf("%s\n",noun1);
printf("Now enter another noun!\n");
scanf("%s\n",noun2);
printf("Now please enter an adjective!\n");
scanf("%s\n",adj);
/* It all comes together here. The code is supposed to take the strings set previously and put them into this story. */
/* The dashes and various /n's are there to make the final Mad Lib easier to read */
printf("\n\nHere is your Mad Lib:\n------------------------------ \nHolly %s down to the %s.\nOnce she got there she bought some %s and ate it!\nAfterwards, Holly brought it home and let her %s eat it.\nHolly is a %s girl!\n------------------------------ \n",verb,loc,noun1,noun2,adj);
return 0;
}
It was made using a combination of Vi and Sublime Text 2 on Ubuntu.
Like I said, I'm not getting any errors when compiling and everything seems to be in order, the problem is that once I run it in the Terminal I have to enter the first answer (answer to "Welcome to Mad Libs! Answers can only be one word long. Please enter a verb.") twice and it takes both of them.
Please try running it yourself (it should work in both OS X and Linux as a .c file) if you're confused as to what I mean, I honestly don't know how to describe the error very well. It makes me input the first answer twice and causes problems when showing the final mad lib.
Just use scanf("%s", ...), not scanf("%s\n"). The \n doesn't get there until later. (Oh, and this is also a good way to get buffer overflows, by the way, so you might consider using fgets, et. al.)
The way it's working right now is:
You type a line and press Enter. scanf gets the line, but without the \n, so it's still waiting.
You type the next line and press Enter. scanf now has the \n at the end of the previous line and uses that string. The first line was read, the second line is now in the buffer, and scanf is awaiting another \n that already exists.
GOTO 2
And that has the effect of shifting all of the answers by one.

C program output in wrong order Eclipse

I have set up Eclipse for c programming on my Windows machine, I have successfully run a "hello, world" program. However, when I try to ask for user input and run the program the console on Eclipse is displaying in the wrong order.
Here is what I have
#include <stdio.h>
int main(void){
char letter;
printf("Please enter a letter:\n");
scanf(" %c, &letter);
printf("The letter you have selected is: %c", letter);
return 0;
}
This program builds just fine, and it runs just fine outside of Eclipse. But when I run it in Eclipse I get the output:
E <--- (this is my user input)
Please enter a letter:
The letter you have selected is: E
I'm not sure why the output is executing in the wrong order, so any help would be much appreciated! Thank you.
Yeah, Eclipse will buffer a certain amount of output (I don't remember how much off hand) before it will appear in the output window. Eclipse is communicating with the attached process through a pipe which is fully buffered. It won't flush until either fflush() is called or the buffer is full. I found that when debugging with Eclipse, things work best if I put the following near the beginning of my application:
setvbuf(stdout, NULL, _IONBF, 0);
This will cause stdout to flush immediately whenever it is written to. If you want to use that for debugging and turn it off otherwise, you can conditionally compile it:
#ifdef DEBUG
setvbuf(stdout, NULL, _IONBF, 0);
#endif
No need to put fflush() everywhere this way.
Edit
Here's where I found the solution when I first ran into this issue myself.
http://wiki.eclipse.org/CDT/User/FAQ#Eclipse_console_does_not_show_output_on_Windows
Eclipse's console is not a true console or terminal but rather eclipse is communicating with the attached process through a pipe which is fully buffered not line buffered. This is why a newline '\n' does not cause the buffer to be flushed.
It sounds like Eclipse is buffering the output of your program and not displaying it right away. This indicates that the "run within Eclipse" feature is not intended to run interactive programs.
You could try adding fflush(stdout); after the first printf, but you shouldn't have to do that just to make your program work in a particular environment.
Try adding fflush(stdout); after the first printf. This has a decent chance of being of help, in case Eclipse does not auto-flush after '\n'.
Yes, fflush()ing buffers is necessary to keep the console's screen updated ...
... but please guys, it's not Eclipse's fault in- and output might get out of sync, but the library's in use!

How can I see an the output of my C programs using Dev-C++?

I'm looking to follow along with The C Programming Language (Second Addition) on a machine running Vista.
So far, I've found Dev-C++ the easiest IDE to do this in. However, I still have one problem. Whenever I run my compiled code, for example: a simple hello world program, it runs, but the console window just flickers on the screen, and I can't see the output.
How can I see an the output of my C programs using Dev-C++? I found a C++ specific solution, System("pause"), and a really ugly C solution, while looping fflush(stdout), but nothing nice and pretty.
I put a getchar() at the end of my programs as a simple "pause-method". Depending on your particular details, investigate getchar, getch, or getc
In Windows when a process terminates, the OS closes the associated window. This happens with all programs (and is generally desirable behaviour), but people never cease to be surprised when it happens to the ones they write themselves.
I am being slightly harsh perhaps; many IDE's execute the user's process in a shell as a child process, so that it does not own the window so it won't close when the process terminates. Although this would be trivial, Dev-C++ does not do that.
Be aware that when Dev-C++ was popular, this question appeard at least twice a day on Dev-C++'s own forum on Sourceforge. For that reason the forum has a "Read First" thread that provides a suggested solution amongst solutions to many other common problems. You should read it here.
Note that Dev-C++ is somewhat old and no longer actively maintained. It suffers most significantly from an almost unusable and very limited debugger integration. Traffic on the Dev-C++ forum has been dropping off since the release of VC++ 2005 Express, and is now down to a two or three posts a week rather than the 10 or so a day it had in 2005. All this suggest that you should consider an alternative tool IMO.
Use #include conio.h
Then add getch(); before return 0;
The easiest thing to do is to run your program directly instead of through the IDE. Open a command prompt (Start->Run->Cmd.exe->Enter), cd to the folder where your project is, and run the program from there. That way, when the program exits, the prompt window sticks around and you can read all of the output.
Alternatively, you can also re-direct standard output to a file, but that's probably not what you are going for here.
For Dev-C++, the bits you need to add are:-
At the Beginning
#include <stdlib.h>
And at the point you want it to stop - i.e. before at the end of the program, but before the final }
system("PAUSE");
It will then ask you to "Press any key to continue..."
Add this to your header file #include
and then in the end add this line : getch();
You can open a command prompt (Start -> Run -> cmd, use the cd command to change directories) and call your program from there, or add a getchar() call at the end of the program, which will wait until you press Enter. In Windows, you can also use system("pause"), which will display a "Press enter to continue..." (or something like that) message.
Add a line getchar(); or system("pause"); before your return 0; in main function.
It will work for you.
;
It works...
#include <iostream>
using namespace std;
int main ()
{
int x,y; // (Or whatever variable you want you can)
your required process syntax type here then;
cout << result
(or your required output result statement); use without space in getchar and other syntax.
getchar();
}
Now you can save your file with .cpp extension and use ctrl + f 9 to compile and then use ctrl + f 10 to execute the program.
It will show you the output window and it will not vanish with a second Until you click enter to close the output window.
i think you should link your project in console mode
just press Ctrl+h and in General tab select console.
When a program is not showing or displaying an output on the screen, using system("pause"); is the solution to it on a Windows profile.
The use of line system("PAUSE") will fix that problem and also include the pre processor directory #include<stdlib.h>.
Well when you are writing a c program and want the output log to stay instead of flickering away you only need to import the stdlib.h header file and type "system("PAUSE");" at the place you want the output screen to halt.Look at the example here.The following simple c program prints the product of 5 and 6 i.e 30 to the output window and halts the output window.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b,c;
a=5;b=6;
c=a*b;
printf("%d",c);
system("PAUSE");
return 0;
}
Hope this helped.

Resources