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.
Related
I am trying to implement DMA for char variable. But I am unable to take input. I tried with all the possible cases I know:
//gets(ptr_name);
//scanf("%[^\n]", &ptr_name);
//fgets(ptr_name, name, stdin);
But I can't even enter input data for the character variable ptr_name. I want to take input as "string with space" as input value. How to solve this problem?
And then how to print the entered name in the screen?
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
char* ptr_name;
int name, i;
printf("Enter number of characters for Name: ");
scanf("%d",&name);
ptr_name = (char*)malloc(name);
printf("Enter name: ");
//gets(ptr_name);
//scanf("%[^\n]", &ptr_name);
//fgets(ptr_name, name, stdin);
printf("\n Your name is: ");
puts(ptr_name);
free(ptr_name);
return 0;
}
scanf("%d", ...) does not consume the enter so the next scanf() gets an empty string.
you can use getchar() to consume the enter.
Also, you need to allocate additional byte for the zero at the end of the string / string terminator. See the + 1 in malloc().
As for your questions, your commented scanf() had & before argument 2 which isn't expected (char ** vs. char *) but other than that it will allow spaces in strings. puts() will print the entered name, alternatively you can modify the above printf() to print the name, e.g: printf("\n Your name is: %s", ptr_name);
Lastly, please consult Specifying the maximum string length to scanf dynamically in C (like "%*s" in printf) for dynamically limiting the input size, avoiding buffer overflow.
DISCLAIMER: The following is only "make it work" version of the program above and is not intended for real life use without appropriately checking return codes and limiting the input size:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* ptr_name;
int name, i;
printf("Enter number of characters for Name: ");
scanf("%d",&name);
getchar();
ptr_name = (char*)malloc(name + 1);
printf("Enter name: ");
scanf("%[^\n]", ptr_name);
printf("\n Your name is: ");
puts(ptr_name);
free(ptr_name);
return 0;
}
if you want to get input with spaces you need to use getline():
getline(&buffer,&size,stdin);
here an example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* ptr_name;
int len;
printf("Enter number of characters for Name: ");
scanf("%d",&len);
ptr_name = (char*)malloc(len);
printf("Enter name: ");
getline(&ptr_name, &len, stdin);
printf("\n Your name is: %s", ptr_name);
free(ptr_name);
return 0;
}
can you help me?
i have a problem with char* station;
when i fill my gaps, everithing is alright, but when i am with printf("%d)Input its stations: ",i+1);. It's a problem, i mean: i enter chech-joch-chor-dsh-dsh but i need to enter chech joch chor dsh dsh(these are names of stations,it's an example).So it prints ONLY THE FIRST WORD, i dont why.. check this out please... (i understand that i need to free what i'have taken). Please, explain why it is so, why the first?.. give me a hint..
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
typedef struct info_bus_{
int number;
int begin;
int end;
char* stations;
int time_working;
}info_bus;
int main()
{
info_bus *b=NULL;
int i,n;
char buffer[128];
printf("How many buses u have: ");
scanf("%d",&n);
b=(info_bus *)malloc(n*sizeof(info_bus));
for(i=0;i<n;i++){
printf("Input the number of a bus: ");
scanf("%d",&(b+i)->number);
printf("%d)Input when it starts to work: ",i+1);
scanf("%d",&(b+i)->begin);
printf("%d)Input when it finishes to work: ",i+1);
scanf("%d",&(b+i)->end);
printf("%d)Input its stations: ",i+1);
scanf("%127s", buffer);
b[i].stations = (char*) malloc(strlen(buffer) + 1);
strcpy(b[i].stations, buffer);
printf("Input time working: ");
scanf("%d",&(b+i)->time_working);
}
for (i=0;i<n;i++){
printf("\n[%d].the number of a bus: %d",i+1,b->number);
printf("\n[%d]. Begin at: %d",i+1,b->begin);
printf("\n[%d]. Finishes at: %d",i+1,b->end);
printf("\n[%d]. Stations: %s",i+1,b->stations);
printf("\n[%d]. Time working: %d",i+1,b->time_working);
printf("\n");
}
return 0;
}
but when i use gets()
it is:
scanf("%127s", buffer);
stops reading after encountering a newline. If you want to be able to read multiple words then use fgets():
fgets(buffer, sizeof buffer, stdin);
Note: fgets() will also read the newline character if there's room. You can remove it if necessary:
buffer[strcspn(buffer, "\n")] = 0; /* to remove the newline */
Generally, avoid using scanf() even for other inputs. It's error prone. See: Why does everyone say not to use scanf? What should I use instead?
Also, the cast of malloc() is unncessary. See: What's wrong with casting malloc's return value?
I am unable to take two inputs strings simultaneously in C on Ubuntu. It shows the wrong output.
Simple program:
#include <stdio.h>
main()
{
char s1[20],char s2[20],printf("\nEnter job:");
scanf("%[^\n]s",s1);
printf("Enter hobby:");
scanf("%[^\n]s",s2);
}
Output:
Enter job:student
Enter hobby:
student
It does not allow the input of a second string. How can I overcome this bug?
If you want to allow embedded spaces, modify the scanf formats this way:
#include <stdio.h>
int main(void) {
char job[100], hobby[100];
printf("Enter job:");
scanf("%99[^\n]%*c", job);
printf("Enter hobby:");
scanf("%99[^\n]%*c", hobby);
printf("%s,%s", job, hobby);
return 0;
}
But be aware that empty lines will not be accepted by this scanf format. The linefeed will stay in the input stream, the second scanf will fail too and job and/or hobby will have indeterminate contents, letting printf invoke undefined behavior.
Is is much more reliable to use fgets() and strip the '\n'.
#include <stdio.h>
#include <string.h>
int main(void) {
char job[100], hobby[100];
printf("Enter job:");
if (!fgets(job, sizeof job, stdin))
return 1;
job[strcspn(job, "\n")] = '\0';
printf("Enter hobby:");
if (!fgets(hobby, sizeof hobby, stdin))
return 1;
hobby[strcspn(hobby, "\n")] = '\0';
printf("%s,%s", job, hobby);
return 0;
}
I want to get only 2 characters in my program. I tried fgets but I can get it to work. How do you suggest that I implement this? Or is there any alternative?
char code[2];
printf("Enter code: \n");
scanf("%s", code);`
I want to limit the number of characters that can be entered to two.
To read two characters and ignore white space you can do:
#include <stdio.h>
int main() {
char code[2];
printf("Enter code:\n");
if (scanf(" %c %c", &code[0], &code[1]) == 2) {
printf("successfully read '%c' and '%c'\n", code[0], code[1]);
}
return 0;
}
to not ignore white space use "%c%c" as the format.
Try this code
#include<stdio.h>
#include<conio.h>
void main()
{
char code;
clrscr();
printf("enter the code\n");
scanf("%2s",code);
printf("%s",code);
getch();
}
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.