I'm really new to AppCode, I've started taking C classes and wanted to use our school license for AppCode.
Most of the others are using CodeLite and make gcc projects, when they build and run it they get a terminal window, is this possible for AppCode?
Also it requires me to input my scanf values first before any other code will be executed (see example below). This way if I have multiple scanf's it requires me to input them all at once which gets really hard to memorize if you have 10's of them.
I've searched a lot on the internet but couldn't find the answers I'm looking for, thanks a lot!
EDIT: Better example
puts("Give a value");
int value;
scanf("%d", &value);
Requires the scanf input before it prints out "Give a value", while in CodeLite it prints out "Give a value" first and afterwards it awaits the scanf input.
Related
Suppose I want to run the following C snippet:
scanf("%d" , &some_variable);
printf("something something\n\n");
printf("Press [enter] to continue...")
getchar(); //placed to give the user some time to read the something something
This snippet will not pause! The problem is that the scanf will leave the "enter" (\n)character in the input stream1, messing up all that comes after it; in this context the getchar() will eat the \n and not wait for an actual new character.
Since I was told not to use fflush(stdin) (I don't really get why tho) the best solution I have been able to come up with is simply to redefine the scan function at the start of my code:
void nsis(int *pointer){ //nsis arconim of: no shenanigans integer scanf
scanf("%d" , pointer);
getchar(); //this will clean the inputstream every time the scan function is called
}
And then we simply use nsis in place of scanf. This should fly. However it seems like a really homebrew, put-together-with-duct-tape, solution. How do professional C developers handle this mess? Do they not use scanf at all? Do they simply accept to work with a dirty input stream? What is the standard here?
I wasn't able to find a definite answer on this anywhere! Every source I could find mentioned a different (and sketchy) solution...
EDIT: In response to all commenting some version of "just don't use scanf": ok, I can do that, but what is the purpose of scanf then? Is it simply an useless broken function that should never be used? Why is it in the libraries to begin with then?
This seems really absurd, especially considering all beginners are taught to use scanf...
[1]: The \n left behind is the one that the user typed when inputting the value of the variable some_variable, and not the one present into the printf.
but what is the purpose of scanf then?
An excellent question.
Is it simply a useless broken function that should never be used?
It is almost useless. It is, arguably, quite broken. It should almost never be used.
Why is it in the libraries to begin with then?
My personal belief is that it was an experiment. It tries to be the opposite of printf. But that turned out not to be such a good idea in practice, and the function never got used very much, and pretty much fell out of favor, except for one particular use case...
This seems really absurd, especially considering all beginners are taught to use scanf...
You're absolutely right. It is really quite absurd.
There's a decent reason why all beginners are taught to use scanf, though. During week 1 of your first C programming class, you might write the little program
#include <stdio.h>
int main()
{
int size = 5;
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++)
putchar('*');
putchar('\n');
}
}
to print a square. And during that first week, to make a square of a different size, you just edit the line int size = 5; and recompile.
But pretty soon — say, during week 2 — you want a way for the user to enter the size of the square, without having to recompile. You're probably not ready to muck around with argv. You're probably not ready to read a line of text using fgets and convert it back to an integer using atoi. (You're probably not even ready to seriously contemplate the vast differences between the integer 5 and the string "5" at all.) So — during week 2 of your first C programming class — scanf seems like just the ticket.
That's the "one particular use case" I was talking about. And if you only used scanf to read small integers into simple C programs during the second week of your first C programming class, things wouldn't be so bad. (You'd still have problems forgetting the &, but that would be more or less manageable.)
The problem (though this is again my personal belief) is that it doesn't stop there. Virtually every instructor of beginning C classes teaches students to use scanf. Unfortunately, few or none of those instructors ever explicitly tell students that scanf is a stopgap, to be used temporarily during that second week, and to be emphatically graduated beyond in later weeks. And, even worse, many instructors go on to assign more advanced problems, involving scanf, for which it is absolutely not a good solution, such as trying to do robust or "user friendly" input validation.
scanf's only virtue is that it seems like a nice, simple way to get small integers and other simple input from the user into your early programs. But the problem — actually a big, shuddering pile of 17 separate problems — is that scanf turns out to be vastly complicated and full of exceptions and hard to use, precisely the opposite of what you'd want in order to make things easy for beginners. scanf is only useful for beginners, and it's almost perfectly useless for beginners. It has been described as being like square training wheels on a child's bicycle.
How do professional C developers handle this mess?
Quite simply: by not using scanf at all. For one thing, very few production C programs print prompts to a line-based screen and ask users to type something followed by Return. And for those programs that do work that way, professional C developers unhesitatingly use fgets or the like to read a full line of input as text, then use other techniques to break down the line to extract the necessary information.
In answer to your initial question, there's no good answer. One of the fundamental rules of scanf usage (a set of rules, by the way, that no instructor ever teaches) is that you should never try to mix scanf and getchar (or fgets) in the same program. If there were a good way to make your "Press [enter] to continue..." code work after having called scanf, we wouldn't need that rule.
If you do want to try to flush the extra newline, so that a later call to getchar might work, there are several questions here with a bunch of good answers:
scanf() leaves the newline character in the buffer
Using fflush(stdin)
How to properly flush stdin in fgets loop
There's one more unrelated point that ends up being pretty significant to your question. When C was invented, there was no such thing as a GUI with multiple windows. Therefore no C programmer ever had the problem of having their output disappear before they could read it. Therefore no C programmer ever felt the need to write printf("Press [enter] to continue..."); followed by getchar(). I believe (another personal belief) that it is egregiously bad behavior for any vendor of a GUI-based C compiler to rig things up so that the output disappears upon program exit. Persistent output windows ought to be the default, for the benefit of beginning C programmers, with some kind of non-default option to turn that behavior off for those who don't want it.
Is scanf broken? No it is not. It is an excellent input function when you want to parse free form input data where few errors are to be expected. Free form means here that new lines are not relevant exactly as when you read/write very long paragraphs on a normal screen. And few errors expected is common when you read from files.
The scanf family function has another nice point: you have the same syntax when reading from the standard input stream, a file stream or a character string. It can easily parse simple common types and provide a minimal return value to allow cautious programmers to know whether all or part of all the expected data could be decoded.
That being said, it has major drawbacks: first being a C function, it cannot directly control whether the programmer has passed types meeting the format specifications, and second, as beginners are not consistenly hit on their head when they forget to control its return value, it is really too easy to make fully broken programs using it.
But the rule is:
if input is expected to be line oriented, first use fgets to get lines and then sscanf testing return values of both
only if input is expect to be free form (irrelevant newlines), scanf should be used directly. But never without testing its return value except for trivial tests.
Another drawback is that beginners hope it to be clever. It can indeed parse simple input formats, but is only a poor man's parser: do not use it as a generic parser because that is not what it is intended for.
Provided those rules are observed, it is a nice tool consistent with most of C language and its standard library: a simple tool to do simple things. It is up to programmers or library implementers to build richer tools.
I have only be using C language for more than 30 years, and was never bitten by scanf (well I was when I was a beginner, but I now know that I was to blame). Simply I have just tried for decades to only use it for what it can do...
I have a problem, i wanted to do a program which will be used to make an account on PC. I write from keyboard name and password which is used to create new user. Everything was okey to the time when i wanted to write command in code, I used "system("net user xxx /add")" where xxx == name of the new user, yes it is working like that, but i want to change xxx to the variable which is written from the keyboard. I mean that, the name of the new user which is creating, the user of program will choose. Any help?
int main()
{
char login;
printf("Login of the new user:");
scanf("%s",&login);
system("net user xxx /add");
return 0;
}
You can use the function sprintf to build a string. It works similar to printf but produces its output in a character array rather than as output to stdout.
For example:
char buffer[100], login[100];
printf("Login of the new user: ");
scanf("%s", login); // notice there is no & operator here
sprintf(buffer, "net user %s /add", login);
system(buffer);
Safer code would use snprintf, which also takes the length of the destination character array as a parameter to ensure that it does not overflow. Also, I'd use fgets rather than scanf as it is inherently safer for the same reason that snprintf is safer than sprintf.
As a side note, for what you're trying to do (add a new user on a Windows system), there are Windows APIs specifically designed for that purpose that you should use rather than calling the net command from system, because these methods will indicate success and failure of attempting to add the user. I concede that there is a very steep learning curve to the Windows API, but if it lets you avoid using the system function, it really is the way to go.
Firstly, you do notscanf towards a variable which is only 1 byte (login). This will just result in buffer overflow and application crash. Since I have the feeling that this is a homework kind of assignment I recommend using an array of chars with help from Since we have snprintf, why we don't have a snscanf?. Otherwise, this answer: C - scanf() vs gets() vs fgets() will give some good directions on how to read (more) safely from the stdin.
Secondly you will need another buffer for creating the net add ... command. For this I recommend using snprintf (https://msdn.microsoft.com/en-us/library/2ts7cx93.aspx) in order to achieve the desired result in a safe manner.
Intentionally I do not post code here to solve this problem, in order to not to hinder your learning, feel free to ask more questions.
Hey guys (and girls),
I have tried and tried to understand this. I have even stepped through with gdb and cannot understand it. So, I'm going to have to bother one of you guys. I have a simple menu where each choice is an integer, 1 through 12, monotonically increasing like normal. Well, I'm trying to code it so that if you select, say, five (5) it begins at there and continues to iterate through by asking name, age, ect. This is for an assignment so please don't tell me how to do that. All I need to know is for choice number 1 I am using an if statement and that if statement begins with these lines...
printf("Enter Name: \n");
gets(name);
printf("Name: ");
puts(name);
printf("\n");
This code works exactly as intended. Then, later in the statement, after doing a few of the same type of thing, except using scanf for a float in the block just before. I have this code...
printf("Enter Major: \n");
gets(major);
printf("Major: ");
printf("\n");
This code will not wait on any input. It just prints out Major: then Major: again on the next line. I can't understand it. I stepped through with gdb and it worked properly when stepping. Then, when I run it the same thing happens again. Would someone please let me know what is going on? Thanks a lot, in advance, for the help. I know the vast majority of the people on here are professionals and don't care to be bugged with things so simple but I just cannot find the answer and my professor has left for the day. THanks guys. -court
Perhaps I should give you guys the code just before the problematic code. It is this, which works as intended...
printf("Enter Height: \n");
scanf("%f", &height);
printf("Height: %f2.1.", height);
The variables involved are declared as... char name[25], major[25]; and float height. Thanks again.
except using scanf for a float in the block just before
is the key to your problem. If you do scanf("%f", &var), and enter a number terminated with a line feed, scanf will NOT read the line feed. Try entering "123abcd" for your float and you'll see the abcd will get stuffed into major.
Use scanf("%f ", &var) to skip over any potential whitespace behind your number (note the blank in the format string).
Besides, you shouldn't use gets, as it may cause buffer overflows, but if you're just starting to learn, this probably isn't your main problem right now.
I have this code.
#include <stdio.h>
int main(void)
{
int dogs;
printf("How many dogs do you have?\n");
scanf("%d", &dogs);
printf("So you have %d dog(s)!\n", dogs);
return 0;
}
To my knowledge, when executing, the program will say 'How many dogs do you have' and I enter a number. Instead, I get a blank page, and I have to first enter a digit. Then I get
How many dogs do you have?
So you have 3 dog(s)! (if I input 3)
I am using Eclipse + MinGW, and its my first time using C, so I'm not sure what I have/had to set up.
I managed to solve this problem. The problem was that eclipse was first processing all the scan statements, and then processing all the print statements. This would be hard to solve if your program has more than one scan statement.
The fix is somewhat simple. Download the binary fix from the following link.
You then need to paste the starter.exe in the path where you have Eclipse installed.
In my case it was this eclipse\plugins\org.eclipse.cdt.core.win32.x86_64_5.2.0.201309180223\os\win32\x86_64
Yours may very a bit. Overwrite the existing starter.exe and it should work.
printf() buffers output. In general (in UNIX) stdlib is smart enough to flush stdout before reading stdin but it might not be the case in MingW. Consider using fflush() or outputting to stderr.
Im writing this program in C and Im having a big problem when I compile it, once I get to the part were I ask the user if hes under 21, if the answer is yes, I ask more questions about that, but when I compile it, the program basicly answers its self. how can I fix this plz?
heres a screenshot, the orange box, i did not answer any of those questions.
http://i.imgur.com/4H3nl.png
You have forgotten to ask the user for input after each question except the first one. Just do scanf("%c", &a); after each question.
In the branch you're having trouble with, you're forgetting to prompt the user for input. Hence, it's reusing whichever answer was last given by the user.
You are reusing the same variable,a, without actually asking for the user input to put into a.
You only read information from the user once. You need to do a scanf before each
if (a == 'y')
only one scanf() function was using which means only once input is acceptable from the stdin stream. for scanf(), when press "enter", the stream stack to 'a'. then stdin stream is NULL. so before each question, should use scanf() once.