I know this question gets asked a hundred times over, and I've scoured all of the possibilities, but I guess I'm not adept enough to know where this problem lies. I'm programming a program where I need to fill a struct with data (ints and strings). The first time I tried it it skipped over everything but the first one, but I didn't panic since I remembered from class I needed to use fflush(stdin) to overcome this. Websites I've searched vote against use of fflush(stdin), since it has undefined behaviour. They say using getchar() would eat the extra newline, thus fixing the problem. Hence my code:
int manNode(){
Item *p;
int helper;
p = (Item*)malloc(sizeof(Item));
printf("Welk type? (Taak:1, Examen:2, Voordracht:3)\n");
scanf("%u",&helper); //selecting an itemtype
if (helper < 1 || helper > 3)
{
printf("wrong value, please try again");
return 0;
}
getchar(); //I've just put getchars everywhere for safety.
p->entrytype = helper-1;
helper = 0;
printf("Vul een naam in:\n");
scanf("%s", p->name); //this one fills in fine
getchar();
printf("Vul een vaknaam in: \n");
scanf("%s", p->course); //this one gets skipped if I type more than one letter in the last scanf()
getchar();
printf("Vul een starttijd in:\n"); //From here on out everything gets skipped
p->start = getTijd();
checkTijd(p->start);
printf("Vul een eindtijd in: \n");
p->end = getTijd();
checkTijd(p->end);
I know it's a bit messy, but focus on the scanfs and getchars. getTijd() also has a couple of scanfs in it that scan for integers, they also get skipped. I don't know where to go from here. (The code isn't incomplete, the rest is just irrelevant)
you can define a new getchar
#include <stdlib.h>
#include <stdio.h>
#define getchar(x) (scanf("%c", x))
int main ()
{
char x, y[10];
getchar(&x);
scanf("%s", y);
printf("got %s\n", y);
return 0;
}
update: this may be a better approach
#include <stdlib.h>
#include <stdio.h>
void work_to_do()
{
#define getchar(x) (scanf("%c", x))
char x, y[10];
getchar(&x);
scanf("%s", y);
printf("got %s\n", y);
#undef getchar
}
int main ()
{
work_to_do();
return 0;
}
to solve the scanf newline ignorance and getchar (but still scanf ignores whitespace)
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#define __getchar() (read(2, NULL, 1)) // 2 stands for standard error, we can make the user enter a character.
void work_to_do()
{
char y[10];
__getchar();
scanf("%s", y);
printf("got %s\n", y);
__getchar();
}
int main ()
{
work_to_do();
return 0;
}
and it's good to take a look at this:
Read space-separated values from file
scanf works as documented. Also, there is nothing wrong with scanf so long as its function is understood.
I created a copy of your code and distilled it to highlight what you want to do. You will need to fill-in the rest yourself.
In this code you need to enter a digit and press enter. Then enter a string and press enter, etc. Note. the fflush(stdout) statement is part of the standard C implementation per K&R. The fflush forces the contents of the buffer out to the console. This flushing makes for a reasonable user/computer dialog.
#include <stdio.h>
main()
{
char string[100];
int helper;
printf("Welk type? (Taak:1, Examen:2, Voordracht:3)\n");
fflush(stdout);
scanf("%d",&helper); //select an itemtype
if (helper < 1 || helper > 3)
{
printf("wrong value, please try again");
return 0;
}
printf("Vul een naam in:\n");
fflush(stdout);
scanf("%s", &string[0]);
printf("\n%s\n", string);
printf("Vul een vaknaam in: \n");
fflush(stdout);
scanf("%s", &string[0]);
printf("\n%s\n", string);
printf("Vul een starttijd in:\n");
fflush(stdout);
scanf("%s", &string[0]);
printf("\n%s\n", string);
printf("Vul een eindtijd in: \n");
fflush(stdout);
scanf("%s", &string[0]);
printf("\n%s\n", string);
}
This code ran on Eclipse with a Microsoft C Compiler.
Also, let me emphasize that if you enter: 1 AAA BBB CCC DDD and press enter then scanf will get executed five times. In this example, the code would run to completion!
So you need to trace your code logic (in this case a straight line) to see how the scanfs are invoked based on what data is entered.
Hope this helps. Please ask if more questions.
Related
I am getting this error whenever I run my code in visual Studio:
#include <stdio.h>
#include <ctype.h>
int main() {
char username[10];
printf("Enter Username: ");
scanf_s("%[^\n]", &username);
while (isupper(username)) {
if (username == '-') {
printf("Username cannot contain UpperCase Letters");
}
}
}
Error Image
I don't think you can pass whole array to isupper. Also if you don't want to return anything instead of int main() use void main() or just return 0 in the end or when you want to end after your program executed successfully. As for using scan_s or scanf or getline or whatever I won't say anything because its a different matter and your syntax of scanf_s is certainly wrong.
Also following code will not check for any buffer overflow (not a good practice, you will see even though we gave size 20 char array, this code will work even for larger input which is certainly not a good thing). So you can either limit the size of input or better to read an entire line via fgets() (or getline() if available) and parse the string yourself.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(){
char username[20];
printf("Enter Username: ");
// scanf("%[^\n]", username); <--- Instead of this
scanf_s("%20c", username, 20); // <----Try Using this
int i=0;
while (i<strlen(username)) {
if (isupper(username[i])) {
printf("Username cannot contain UpperCase Letters\n");
return 0;
}
i++;
}
return 0;
}
My first guess would be that your while is an endless loop, try to do it like this:
int i;
for(i=0; i<strlen(username);i++){
if(isupper(username[i])){
printf("Username cannot contain UpperCase Letters");
}
}
My code:
#include <stdio.h>
#include <math.h>
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
char a[10],b[10];
puts("enter");
gets(a);
puts("enter");
gets(b);
puts("enter");
puts(a);
puts(b);
}
return 0;
}
Output:
1
enter
enter
surya (string entered by user)
enter
surya (last puts function worked)
How can I use “gets” function many times in C program?
You should never ever use gets() in your program. It is deprecated because it is dangerous for causing buffer overflow as it has no possibility to stop consuming at a specific amount of characters - f.e. and mainly important - the amount of characters the buffer, a or b with each 10 characters, is capable to hold.
Also explained here:
Why is the gets function so dangerous that it should not be used?
Specially, in this answer from Jonathan Leffler.
Use fgets() instead.
Also the defintion of a and b inside of the while loop doesn´t make any sense, even tough this is just a toy program and for learning purposes.
Furthermore note, that scanf() leaves the newline character, made by the press to return from the scanf() call in stdin. You have to catch this one, else the first fgets() thereafter will consume this character.
Here is the corrected program:
#include <stdio.h>
int main()
{
int t;
char a[10],b[10];
if(scanf("%d",&t) != 1)
{
printf("Error at scanning!");
return 1;
}
getchar(); // For catching the left newline from scanf().
while(t--)
{
puts("Enter string A: ");
fgets(a,sizeof a, stdin);
puts("Enter string B: ");
fgets(b,sizeof b, stdin);
printf("\n");
puts(a);
puts(b);
printf("\n\n");
}
return 0;
}
Execution:
$PATH/a.out
2
Enter string A:
hello
Enter string B:
world
hello
world
Enter string A:
apple
Enter string B:
banana
apple
banana
The most important message for you is:
Never use gets - it can't protect against buffer overflow. Your buffer can hold 9 characters and the termination character but gets will allow the user to typing in more characters and thereby overwrite other parts of the programs memory. Attackers can utilize that. So no gets in any program.
Use fgets instead!
That said - what goes wrong for you?
The scanf leaves a newline (aka a '\n') in the input stream. So the first gets simply reads an empty string. And the second gets then reads "surya".
Test it like this:
#include <stdio.h>
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
char a[10],b[10];
puts("enter");
gets(a); // !!! Use fgets instead
puts("enter");
gets(b); // !!! Use fgets instead
puts("enter");
printf("|%s| %zu", a, strlen(a));
printf("|%s| %zu", b, strlen(b));
}
return 0;
}
Input:
1
surya
whatever
Output:
enter
enter
enter
|| 0|surya| 5
So here you see that a is just an empty string (length zero) and that b contains the word "surya" (length 5).
If you use fgets you can protect yourself against user-initiated buffer overflow - and that is important.
But fgets will not remove the '\n' left over from the scanf. You'll still have to get rid of that your self.
For that I recommend dropping scanf as well. Use fgets followed by sscanf. Like:
if (fgets(a,sizeof a, stdin) == NULL)
{
// Error
exit(1);
}
if (sscanf(a, "%d", &t) != 1)
{
// Error
exit(1);
}
So the above code will automatically remove '\n' from the input stream when inputtin t and the subsequent fgets will start with the next word.
Putting it all together:
#include <stdio.h>
int main()
{
int t;
char a[10],b[10];
if (fgets(a,sizeof a, stdin) == NULL)
{
// Error
exit(1);
}
if (sscanf(a, "%d", &t) != 1)
{
// Error
exit(1);
}
while(t--)
{
puts("enter");
if (fgets(a,sizeof a, stdin) == NULL)
{
// Error
exit(1);
}
puts("enter");
if (fgets(b,sizeof b, stdin) == NULL)
{
// Error
exit(1);
}
puts("enter");
printf("%s", a);
printf("%s", b);
}
return 0;
}
Input:
1
surya
whatever
Output:
enter
enter
enter
surya
whatever
Final note:
fgets will - unlike gets - also save the '\n' into the destination buffer. Depending on what you want to do, you may have to remove that '\n' from the buffer.
C-code only: Ask user if they are married or not. User must input 0 for false. User must input any other character for true. Do it using only one printf.
Ok, so I always turn to stackoverflow as a last resort, because I am trying to figure it out. This, is what I came up with but I get errors and I have done other things like take out scanf("%f", &t), because that is essentially unnecessary. I also made char married[3]; char married[] ="; instead but that doesn't work.
Here is my code:
#include <stdio.h>
#include <string.h>
int main()
{
char married[3];
unsigned long t;
int f;
scanf("%f", &t);
scanf("%d", &f);
printf(" For the following question: Enter 0 if false. Enter anything but 0 if true. Are you married? %s", married);
if (f == 0)
{
married == "no";
}
else
married == "yes";
return 0;
}
Thanks the help is appreciated. Please go easy on me just learning...
I'm not sure you are interpreting the question correctly. It says to print whether the person is married or not. So that's the expected output. It suggests you can do that with one printf. It does not mean the whole program only has one printf so you are allowed to have another printf for the user prompt. It just means avoid using two printfs for the output (one for YES and another for NO). One way to do this is to use the ? operator.
For example:
#include <stdio.h>
#include <string.h>
int main(void)
{
int married = 1;
printf(" For the following question: Enter 0 if false. Enter anything but 0 if true. Are you married?");
scanf("%d", &married);
printf("You %s married\n", married ? "ARE" : "ARE NOT");
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char married[4]; //Space for 'yes' + the NUL-terminator
//unsigned long t; Why do you have this?
int f = 1; //Initialize variables
//scanf("%f", &t); ??
//scanf("%d", &f); Wrong place
printf(" For the following question: Enter 0 if false. Enter anything but 0 if true. Are you married?"); //Remove %s and the argument. You are trying to print an uninitialized array
scanf("%d", &f); //scan input after printing
if (f == 0)
strcpy(married, "no");
else
strcpy(married, "yes"); //Copy strings using strcpy function
return 0;
}
I'm trying to find the bug here, but still don't get it.
I've been debugging and googling it and found some close topics, but there are only solutions which I don't need ATM, and I'm curious why this code is not working:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define BUFFER 256
int main()
{
int missionCode;
char *desc = (char*)malloc(sizeof(char)*BUFFER);
do {
printf("Please enter the mission code (or -1 for exit): ");
scanf("%d", &missionCode);
fflush(NULL);
if (missionCode==-1)
return 1;
} while (missionCode>10);
do {
printf("Please enter a string:\n");
scanf("%[^\n]s", desc); //it doesn't stop here!
fflush(NULL);
if (!strcmp("exit",desc))
return 1;
} while (strlen(desc)<20);
printf("your string:\n%s", desc);
return 0;
}
There's something wrong with the scanf\flushall in the second loop, but I don't find out what.
BTW, this is C ofcourse.
scanf("%d", &missionCode);
leaves the newline in the buffer, so
scanf("%[^\n]s", desc);
immediately finds one and stops. You can add a space
scanf(" %[^\n]s", desc);
to the format to skip initial whitespace.
This simple issue is causing my entire program to crash during the first input. If I remove the input, the program works fine but once I add scanf into the code and enter the input the program crashes.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXEMPS 3
// stub program code
int main (void){
char answer;
do
{
printf("\n Do you have another(Y/N): ");
scanf("%c", answer);
}while(answer == 'Y' || answer == 'y');
getchar();
printf(" Press any key ... ");
return 0;
} // main
You must pass the address of the variable to scanf:
scanf("%c", &answer);
Use "&answer". And get rid of the extraneous "fflush()" commands...
Better, substitute "answer = getchar ()".