FAQ Database Discussion Community


Stop scanf loop if user enters a specific number (Not working) C

c,loops,compare,scanf
I've looked at multiple solutions but none of them worked for me. I'm asking the user to enter numbers in a loop, but if the user enters a specific number the loop should break. This is what I've got so far. #include <stdio.h> #include <stdlib.h> #define MAXNUMBERS 5 int getNumbers(int...

Specifing the maximum string length to scanf dynamically in C (like “%*s” in printf)

c,io,size,buffer,scanf
I can specify the maximum amount of characters for scanf to read to a buffer using this technique: char buffer[64]; /* Read one line of text to buffer. */ scanf("%63[^\n]", buffer); But what if we do not know the buffer length when we write the code? What if it is...

Do white spaces take space in txt files?

c,file-io,whitespace,scanf,fscanf
I'm wondering if the white spaces take space in txt files for C. For example if i'm going to take the file pointer back using fseek() or if I am going to fscanf an input from a file do I need to consider white spaces? A Assume a file has...

Why does command prompt show numbers before I begin?

c,file-io,printf,scanf
The command prompt shows numbers before program begins. Why? 2687688 is given but the numbers won't write to file? #include <stdio.h> #include <conio.h> int main(void){ FILE*nfPtr; int n; if ((nfPtr=fopen("c:\\Users\\raphaeljones\\Desktop\\newfile.dat","w"))==NULL) { printf ("Sorry! The file cannot be opened\n"); } else {//else 1 begin printf("Enter numbers to be stored in file\n");...

C program skips a line when asking for user input [duplicate]

c,char,user-input,scanf
This question already has an answer here: C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf 6 answers printf("Number of tracks: "); fflush( stdin ); scanf("%d", &track); printf("Is this an album or single: "); fflush( stdin ); scanf("%c", &type); when I...

why after looping there's a newline

c,newline,counter,scanf
so i'm trying to make a penalty kick scorekeeper. i set it to be 5 rounds at first, and when the scores are tied, it will repeat another 5 rounds. the problem is there's seem to be a newline appeared after it. #include <stdio.h> int main() { int penalty2=0,penalty1=0,i=0; char...

Why does scanf ask for input twice, but just in the first loop iteration only?

c,scanf
First of all, this may seem duplicate with this question, but in my case, why did this only happen in the 1st loop iteration (input for the 1st array element). Why not all? My code: #include "stdio.h" int main(int argc, char const *argv[]) { int a[5]; int i; for (i...

Replacing gets with scanf in simple equation crashes the program

c,scanf,atoi
I'm working through C for Dummies. It has an example code for converting inches to cm (p.135, if you have the text) using gets and atoi. Now, I wanted to try using scanf rather than the dreaded gets, and this is the best I could come up with (based on...

Printing an int value obtained from user

c,printing,int,scanf,value
The problem is at the age part, the compiler does not give me any errors but when I run it it prints a random number for int age printf("Enter your name:"); scanf(" %s",&name1); int age; printf("\n\nHow old are you?"); scanf(" %d",&age); char gender; printf("\n\nEnter your gender[Male/Female]:"); scanf(" %s",&gender); char confirmation;...

getchar() not working in c

c,while-loop,char,scanf,getchar
getchar() is not working in the below program, can anyone help me to solve this out. I tried scanf() function in place of getchar() then also it is not working. I am not able to figure out the root cause of the issue, can anyone please help me. #include<stdio.h> int...

Simple Unit Conversion Program - scanf issues with do-while loop (C programming)

c,while-loop,scanf
The problem I am having currently is that the program does not follow through to the sections preceding the first scanf command and just skips the entire decision making process and returns to the beginning of the do-while loop. I have read up on other suggestions telling people to use...

scanf issue when reading double

c,gcc,double,user-input,scanf
I'm using MinGW on windows 7 to compile C files. My problem is a strange behaviour with scanf() to read doubles from user input. My code: int main() { double radius = 0; double pi = 3.14159; scanf("%lf \n", &radius); // after the input, it continues waiting... radius = ((radius...

Print each word in a separate line from an input string

c,string,char,printf,scanf
I'm having trouble printing each word in a separate line from an input string in C. The question from the assignment I'm doing states: Take a sentence as input and print its words in separate lines. My Code: #include<stdio.h> int main() { int i; char s[100]; scanf("%s", s); for(i=0; s[i]!='\0';...

Why passing string to scanf() compiles fine in C?

c,scanf,undefined-behavior
I recently wrote a simple program where I by mistake use scanf() instead of printf() for displaying a message on console. I was expecting to get compile time error, but it compiles fine without warnings & crashes at runtime. I know that scanf() is used for taking input from keyboard....

Why does scanf returns control back to the program on pressing Enter key?

c,scanf
I wrote the following program. void main() { int *piarrNumber1 = (int *) calloc(1, sizeof(int)); int iUserInput = 0; scanf("%d", &iUserInput); piarrNumber1[(sizeof piarrNumber1 / sizeof(int)) - 1] = iUserInput; printf("\n%d\n", piarrNumber1[0]); } I input "3" followed by a TAB from the keyboard. Nothing happens. Then, I press Enter Key. I...

How to make fgets() ignore a \n at beginning?

c,string,scanf,fgets
I have below C code. struct student { int rollNumber; char name[20]; char department[20]; char course[20]; int yearOfJoining; }; int main() { // Creating a 'student' variable. struct student s; // Take the info of student from keyboard printf("Student \n-------------------\n"); printf("Roll no: "); scanf("%d",&s.rollNumber); printf("Name: "); fgets(s.name, 20, stdin); //scanf("%s",&s.name);...

Checking input types with scanf() in a while loop [duplicate]

c,scanf
This question already has an answer here: Why is scanf() causing infinite loop in this code? 10 answers I've been writing a program that takes an input and checks if the number is even or odd and outputs an error message if the input is a character not a...

How do you type something on the same line of text in C [closed]

c,printf,scanf
I was wondering how can you type something in one line in C? This is the normal way it outputs. Output > <text> Instead > <text> ...

if statement for string comparison is not executing properly

c,string,input,printf,scanf
I am trying to write a simple program for finding out areas of different shapes.The program is compiled fine but when it runs it does not give me the right answer. I mean When it runs it asks: What do you want to find area of? and when I type...

I'm not able to use scanf() in else statment

c,if-statement,scanf
can we use scanf() function in else , like i used in this code. Bec i'm not able to enter value(char) for sex variable. so i want to why i'm not able to enter the value for sex variable ? #include<stdio.h> #include<conio.h> void main() { clrscr(); int age; char s,ms;...

Spaces with scanf in a client to server message. C

c,client,server,scanf
I'm developing a client/server multithread program in C. I need to send a message from client to server with a scanf but when in the client puts a space the scanf see it as a newline. How can I read an input message with scanf including spaces? (and so the...

How to get each element of a array from user input then pass it to a function in another file in C

c,arrays,function,scanf,elements
How can I get each element of an array from user input then pass it to a function in another file. I'm having trouble and need help please. This my code. main.c #include <stdio.h> #include "lab8.h" int x[100]; int y[100]; int main(void) { int count, i, product; printf("Enter the length...

How to break a string, that was read using fgets(), using scanf(“%s”,..)

c,buffer,scanf,fgets
I am working on a program that takes a mathematical expression, transforms it to posfix notation and then solves it. First I am checking the expression to see if it is well formed ( Open brackets and parenthesis matches the closing ones ). To do the part of checking I...

C - Using file as database

c,database,file,scanf
i'm using VS2013 i have structure like : typedef struct StuInformation { char studentNumber[100]; char name[50]; char sex[10]; unsigned short age; char m_status[10]; } student; i want to get the information from user one by one : student std; int RecordSize; printf("pls insert the student number :\n"); scanf_s("%[^\n]",std.studentNumber); printf("name :...

How to introduce string by keyboard in child after fork

c,concurrency,process,signals,scanf
I'm exercising over concurrency in C, I wrote a small and simple program in which a parent process creates two children, sender and receiver. Sender will read from stdin a string and then procede to send it in some way to receiver (not relevant). The real problem here is that...

Trouble with delimiting colon with scanf

c,scanf
I am having some trouble using scanf. The input I want to read will be this format: string:integer: For instance, ptest/src/test.c:19:blahblahblah Would be a valid string. I want to store p2test/src/test.c and 19. However, I've run into some problems, namely, 19 does not get read in. Here is what I...

Simple scanf does not set variable value

c,scanf
I wrote this simple and short code in C and can't get it to work properly: #include <stdio.h> int main(void) { char var1[2]; int var2, var3; unsigned char var4; scanf("%s %d %d %d", var1, &var2, &var3, &var4); printf("%s %d %d %d\n", var1, var2, var3, var4); return 0; } If I...

skipped trouble with getchar and scanf

c,ubuntu,scanf,getchar
I recently started to program in C and im having trouble with this code: #include <stdio.h> #include <stdlib.h> #define PI 3.1416 int main () { float x; int y; x = PI; printf("Enter y: "); scanf(" %i", &y); printf("The new value of y is: %i.\n\n",y); x = x * y;...

Why isn't scanf( ) waiting for input from keyboard?

c,printf,structure,scanf,fflush
I have below C code. #include<stdio.h> int main() { //Declaring structure book. struct book { char name; float price; int pages; }; struct book b[5]; int i; //Below loop takes the info if 5 books from user for (i=0; i<5; i++) { printf("Enter name, price, and pages: "); fflush( stdin...

Parse string separated with semicolon using a regex

c,scanf
I'm trying to separate a string of numbers using a regex. The following C code works when the numbers are separated with a comma: #include <stdio.h> int main() { char *multiple = "0.20,0.37,0.75,0.56"; char one[4]; char two[4]; char three[4]; char four[4]; sscanf(multiple, "%[^','], %[^','], %[^','], %[^',']", one, two, three, four);...

Scanf() working differently with \n and '\n' supplied in format specifier

c,scanf
#include "stdio.h" int main(){ float longi; float lati; char info[80]; int started = 0; puts("Data=["); while((scanf("%f\n%f\n%s",&lati,&longi,info))==3){ //here is my doubt. printf("\n{latitude:%f, longitude:%f, info:%s},",lati, longi, info); } puts("\n]"); } The above code works as desired, but I figured it out by trial and error. This takes three inputs with the 'enter'...

Storing scanf values into a 2d string array

c,scanf
I am having trouble storing strings into a 2d array using scanf. To illustrate, this is the input the program accepts: p2/src/stuff:5: p3/src/stuff:5: p4/src/stuff:6: So I want to be able to split the strings and numbers by colons and store them separately. So ideally, my 2d array would look like...

Storing a string of inputs into a struct in C

c,string,struct,user-input,scanf
was wondering how I would be able to store a user inputted string in the format "string,character,integer,integer" into a struct. For example storing "apple,c,5,10" into typedef struct { char item[80]; char letter; int x,y; }information; information apple; I am trying to avoid going through using scanf and a long piece...

second scanf to recognize keyword to exit iteration of integers? C

c,scanf
Trying to accept integers separated by either spaces or lines until the user types the keyword "end" at which time the program will look for an operator (+ - * /) to perform the action on the entered integers. I keep getting the "comparison between pointer and integer" warning when...

End while loop with ctrl+d, scanf?

c,while-loop,printf,scanf,eof
I want the user to be asked "how many circles" they wanna write until the user decides to end it with (Ctrl+d) which is EOF? extra question: if I write a letter for example "k" it will spam out circles. How do I change that? #include <stdio.h> int main ()...

Shortening strings in C

c,string,scanf
I'm trying to shorten a string length to be displayed (printf). For example I ask user to enter a name, then the program will only display back 15 characters of it. This is snippet of my code: int score1=0,score2=0,foul1=0,foul2=0,rebound1=0,rebound2=0,assist1=0,assist2=0,missed1=0,missed2=0,choice1,choice2,choice4,choice5=0; char choice3,home[15]="HOME",away[15]="AWAY"; printf("\t\t\t==================================\n\t\t\t|| NETBALL SCOREKEEPER\t||\n\t\t\t==================================\n\n"); do { printf("Do you want to...

Why fgets takes cursor to next line?

c,string,cursor,scanf,fgets
I have taken a string from the keyboard using the fgets() function. However, when I print the string using printf(), the cursor goes to a new line. Below is the code. #include<stdio.h> int main() { char name[25]; printf("Enter your name: "); fgets(name, 24, stdin); printf("%s",name); return 0; } And below...

scanf a big hexadecimal value

c,hex,scanf
I have a issue trying to use scanf to get a big hexadecimal num (12 chars) from the user. it seems to only get the last 8 chars, eg - ABFFFFFFFF will become 0000FFFFFFFF. this is my code - unsigned long long address; scanf("%x",&address); printf("Address: %#014x", address); for this input:...

How to read and write files using printf and scanf in C? [closed]

c,file,printf,scanf
A little backstory: Some years ago, I was on a algorithm contest. By that time, I was learning C, and I didn't know how to write or read files using the normal methods. In order to no get confused by new methods and syntax, a C wizard, told me to...

Reading from txt file in C using scanf

c,file,scanf,sscanf
i have a txt file and i want to read from it. I know that i will have to read 20 lines(each line contain 3 number variables,for instance 10 5 6 and so on) #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int x,y,z; int counter = 0;...

C sscanf (fscanf) behaving differently row from row

c,scanf,fscanf,sscanf
I've this snippet of code which should read text from input file and put it in a struct. void load(FILE *fin, struct camion payload[]){ int i=0; char except; char buf[1000]; while (fgets(buf,sizeof(buf),fin)){ except='A'; sscanf(buf,"%i-%i-%i %i %s %c",&payload[i].day,&payload[i]. month,&payload[i].year,&payload[i].nparcels,payload[i].origin,&except); if (except=='E') payload[i].except=1; i++; } } The fgets works as it should...

Why can't I input values?

c,visual-studio-2013,scanf
I can't input values without an error popping up, even though the code is correct. #include <stdio.h> int main() { char name[100]; printf("Enter your name: "); scanf_s("%s", name); printf("Your Name is: %s", name); return 0; } As soon as I input a value to the name and press enter, an...

Reading from a CSV file and solving problems with “;”

c,csv,scanf,delimiter
I have this CSV file and I have to read it and print each different customer (each line is a customer) IDClient;Name;Surname;Address;City;State;Postal_Code 111A;Howard;Snyder;2732 Baker Blvd.;Eugene;OR;97403 222B;Yoshi;Latimer;City Center Plaza 516 Main St.;Elgin;OR;97827 333C;John;Steel;12 Orchestra Terrace;Walla Walla;WA;99362 444D;Jaime;Yorres;87 Polk St. Suite 5;San Francisco;CA;94117 I wrote this code and despite some warnings seems...

Why value of second variable is irrelevant after adding space or new line?

c,scanf
I'm newbie in programming learning C language.I'm little confused right now.I tried to Google about it but can not find out the satisfactory result so i thought to sort out by asking the question in this website.Have a look at this short program #include<stdio.h> int main() { int num1,num2; printf("enter...

C program loops infinitely after scanf gets unexpected data

c,scanf
I have a program where I want the input integer to be between 2 and 64 inclusive, so I put scanf inside a do { ... } while loop. Here's the code I initially tested: int initialBase; do { printf("Initial base: "); scanf("%i", &initialBase); } while (initialBase < 2 ||...

Getting a char* with spaces in C from sscanf

c,char,scanf
I am attempting to read a line written in the format: someword: .asciiz "want this as a char*" There is an arbitrary amount of white space between words. I am curious if there is a simple way of getting the internal characters in the quotes into a char* variable using...

scanf int8_t corrupts stack

c++,visual-studio-2013,scanf
How to scanf int8_t and other types without this error. I used "cinttypes" to get constants of patterns but that didn't help. #include <cstdio> #include <cstdint> #include <cinttypes> int main() { int8_t var; scanf("%" SCNi8, &var); printf("%" PRIi8 "\n", var); return 0; } P.S. This error occures only in Debug,...

Find the lonely integer in an array

c,arrays,pointers,scanf
Please refer to this hackerrank challenge if you can. The problem is to find the lonely integer in an array, given an array consists of only pairs except one lonely integer. The problem is with this test case 9 4 9 95 93 57 4 57 93 9 9 is...

How to read input in C

c,scanf
I'm trying to read a line with scanf("%[^\n]"); right before it I'm reading an integer with "%d", was told to me that scanf doesn't erase the '\n' after reading, so I have to call fflush() to avoid it, but even doing that I still have the same problems, so here...

What does a # sign after a % sign in a scanf() function mean?

c,input,printf,scanf,format-specifiers
What does the following code mean,in C scanf("%d%#d%d",&a,&b,&c); if given values 1 2 3 it gives output as 1 0 0 P.S- I know it is used with printf() statement but here in scanf() statement it gives random behaviour....

Please explain this output of the code

c,function,return,printf,scanf
#include<stdio.h> int GetPositiveInt(void); int main(void) { int num = GetPositiveInt(); printf("%d",num); return 0; } int GetPositiveInt(void) { int n; do { printf("Enter a positive number : "); scanf("%d",&n); }while(n<=0); } The output is the value of n but I don't know how it is returned to num. Does scanf() and...

C: Format %s expects argument of type char* in funny strings program

c,string,scanf
I am making a program to check for funny strings. To understand the exercise read this. My code is here: #define MAX_STR_LENGTH 10 char* reverse(char *str) { char *reversedStr = malloc(strlen(str)); for (int i = 0; i < MAX_STR_LENGTH; i++) { for (int j = MAX_STR_LENGTH - 1; j >...

Why doesnt getchar() stop reading strings in C?

c,string,input,scanf,getchar
I want the user to be able to input a number n and then the program will read n strings from the user. But now the program wont stop reading strings. #include <stdio.h> #define STRING_MAX 10 int main (void) { char string[STRING_MAX]; int count; int total; int n, i; int...

Why compiler is not issuing error while passing an int (not int *) as the argument of scanf()?

c,scanf,undefined-behavior
I tried the below c program & I expected to get compile time error, but why compiler isn't giving any error? #include <stdio.h> #include <conio.h> int main() { int a,b; printf("Enter a : "); scanf("%d",&a); printf("Enter b : "); scanf("%d",b); printf("a is %d and b is %d\n",a,b); getch(); return 0;...

Scanning values in C till hit a new-line char, '\n'

c,arrays,algorithm,scanf,getchar
How can I scanf() the integer values I enter into an array until I hit enter. I believe I can use getchar() != '\n'. but how do I loop through the line ? Suppose my input is 20 21 2 12 2. I want an array that has all those...

Why does my program accept one integer too many and input one too few?

c,arrays,scanf
I'd like to understand why the program allows me to input 3 integers when I have defined SIZE as 2. And when it returns the array it only returns two numbers NOT the three I have entered.Thanks for your help. //C How to Program Exercises 2.23 #include <stdio.h> #include <conio.h>...

scanf in a while loop reads on first iteration only

c,scanf
NOTE: Please notice this is not a duplicate of Why is scanf() causing infinite loop in this code? , I've already seen that question but the issue there is that he checks for ==0 instead of !=EOF. Also, his problem is different, the "infinite loop" there still waits for user...

scanf in while loop only works on first iteration

c,while-loop,scanf
I am writing a program to analyze memory dumps left by an emulator that I am writing. You can input a memory address and the size of the value you wish to view in order to view the contents of the memory dump. I have the code running in a...

how to scan a string input

c,arrays,string,segmentation-fault,scanf
I am trying to get an input string by using scanf() in a function, but it keeps failing and I don't know why. Here is part of my code. typedef struct node { int id; char * name; char * address; char * group; struct node * next; } data;...

Strange C++ behavior. Value gets overriden

c++,scanf,undefined-behavior
#include <iostream> #include <stdio.h> using namespace std; int main(){ int t; scanf("%d",&t); while(t--){ long long int val; char op; scanf("%lld",&val); while(true){ long long int x; scanf("%s",&op); if(op=='=')break; scanf("%lld",&x); cout<<"***"<<t<<endl; if(op=='+')val+=x; else if(op=='-')val-=x; else if(op=='*')val*=x; else val/=x; } printf("%lld",val); } } In the above code, I can't understand why the value...

C++ — error C2664: 'int scanf(const char *,…)' : cannot convert argument 1 from 'int' to 'const char *'

c++,scanf
I'm very new to C++ and I'm trying to build this very simple code, but I don't understand why I get this error: Error 1 error C2664: 'int scanf(const char *,...)' : cannot convert argument 1 from 'int' to 'const char *' Here is the code: // lab.cpp : Defines...

How to limit input length with scanf

c,arrays,scanf
In this program I have taken a dimensional character array of size[3][4] as long as I enter a 3 characters for each row it will work well. For example if I enter abc abd abd I get the same output but if i enter more letters in the first or...

How does scanf determine whether to block?

c,scanf,io-redirection
When I redirect a file to stdin using MyProgram < cl.txt command from the command line, scanfs doesn't wait me to press Enter. But when I use scanf in my program without doing so, it does block until enter key is pressed. How exactly does it determine that? Does it...

Segmentation Fault after 5th scanf

c,scanf,sigsegv
This code gives a Segmentation Fault at the exact 5th line of input. If n<5 or in the debugger everything is fine. scanf("%d %d",&n,&x); m=(int**)malloc(n*sizeof(int)); for(i=0;i<n;i++) { m[i]=(int*)malloc(2*sizeof(int)); } for(i=0;i<n;i++) { scanf("%d %d",&m[i][0],&m[i][1]); }` ...

Nonportable Pointer Conversion

c,scanf,turbo-c
I wrote the code and compiled it with Turbo C. But it always got the "Nonportable Pointer Conversion" error. Any ideas? #include "stdio.h", "conio.h" void main(){ char gender; clrscr(); printf("Please enter your gender (M/F): "); scanf("&s", gender); if(gender == "M"){ printf("Male"); } else if(gender == "F"){ printf("Female"); } else {...

Issue with scanf(“%s”)

c++,scanf
include <iostream> #include <stdio.h> using namespace std; int main() { int n; scanf("%d",&n); int l,k; for(int i=0;i<n;i++) { scanf("%d %d",&l,&k); char ch[l+1]; /****/ scanf("%s",ch); printf("Are we here"); char ci=ch[0]; int flips=0; int count=0; for(int j=0;j<l;j++) { if(ch[j]==ci) { count++; if(count>k) { flips++; count=1; if(ci=='1') { ci='0'; ch[j]='0'; } else if(ci=='0')...

How to get several value in once enter ?(Number of uncertainty)

c,scanf
How can I get several values input from the keyboard (an integer type and many number of uncertainty) ? I need to write a program which allow users to enter any number , Each number is delimited by the Space and when the user presses Enter, The number was placed...

Program immediately terminates with segfault when using scanf

c,pointers,segmentation-fault,scanf
When I use gets() or fgets() instead of scanf(), the program does execute completely but prints segmentation fault(core dumped) in the end! I don't understand why am I getting segfault in both the cases. Here is the code for converting an infix to postfix exp using stacks. #include<stdio.h> #include<stdlib.h> #include<string.h>...

C Wrong Answer when squaring

c,printf,scanf
I'm learning C using C by Example. There is a question where we need to take an input integer and square it and print it to the screen. I'm having a strange error, when no matter what Int I enter it give me this output: Please enter a number. 5...

Add and print multiple char in C [closed]

c,char,int,add,scanf
I'm creating a Dice Game, where the user rolls 3 dice and gets some random outputs (up to integer 6). My next step is to add those 3 values obtained and get its sum. How do I achieve this? Any suggestion would be helpful. Here's my source code: //Roll-a-dice Game!...

What does %[^<] (and friends) mean in the formatted string family?

c,string-formatting,scanf
A comment (which should probably be submitted as an answer) has the code sscanf(string, "<title>%[^<]</title>", extracted_string); Running the code seems to copy the text between the <title> tags to extracted_string, but I cannot find any references to a caret in the printf family, either in the man pages or elsewhere...

How to use scanf for a char array input?

c,arrays,scanf
I set a char array of size of 10 and want to check the real size of the input permitted. I tested 123456789; 1234567890; 123456789123456789 Interestingly, all of them passed and got the right output which are 123456789; 1234567890; 123456789123456789 It confused me a lot because I thought the last...

Specifying the ']' character in a C/C++ scanf() scanset

c++,c,format,scanf
I would like to use a scanf family function to extract a string delimited by ']'. For a delimiter of ')' one can do this: scanf(" %80[^)]", &buf); But how do you include the ']' in the scanset in general (not just the negated set case example above)? Is there...

In C, Why does my float print out as 0 even though I input 13.5 for it using scanf?

c,arrays,floating-point,printf,scanf
I am very new to C programming. I'm having trouble figuring out why my float variable keeps printing out 0 when I input it as a number. Thanks for the help in advance! Code: int num, month, day, year; float price[10000]; printf("Enter item number: \n"); scanf("%d", &num); printf("Enter unit price:...

scanf() to get in the string on the second time

c,scanf
What is wrong with the scanf() to get in the string on the second time, I can't input my string on the second time. I am not sure with the error that occurs, I can't get this program function well #include <stdio.h> #include <stdlib.h> int main() { //variables decleration char...

scanf takes extra parameter why?

c++,c,scanf
I'm new to c++ & its developing I used to scan to take input parameters. But I gave two input parameters. But program allows me to enter extra parameter. Please explain me why this happened. Please find below the code I I used. #include <iostream> int main(int argc, const char...

Is there any way in C to terminate scanf() inputting in array without ctrl+d?

c,arrays,input,scanf
For example :I want to terminate inputting without using (ctrl+d or pressing any character) as doing this cause the program to execute and the second scanf() does not work.I am not allowed to input number of elements in the array. for(i=0;a[i]<10000;i++) { if(scanf("%d",&a[i])==1) count++; } for(j=0;a[j]<10000;j++) { if(scanf("%d",&b[j])==1) count1++; }...

scanf get multiple values at once

c,char,segmentation-fault,user-input,scanf
I need to get in one single shot different inputs from one single line. In particular I need to get a single char and then, depending on which char value I just read, it can be a string and an int or a string, an int and another string and...

scanf doesn't work (integer)

c,scanf
When I execute my code, scanf("%d", &n); don't scan anything, I mean, if I introduce any number it doesn't do anything, regardless of the numbers I introduce. void testEsPrimo() { int n; printf("Comprobando si un número es o no primo\n"); printf("Teclee un número entero: "); fflush(stdout); scanf("%d", &n); //<---- The...

scanf crops last byte of numbers

c,scanf
Take a look at this program: #include <stdio.h> int main() { unsigned i = 0; char type = 'a'; int result = scanf("%u%[asd]", &i, &type); printf("result = %d, i = %u\n", result, i); return 0; } It should accept a number then a character that is either a, s or...

Dynamically allocate user inputted string

c,arrays,user-input,scanf,dynamic-memory-allocation
I am trying to write a function that does the following things: Start an input loop, printing '> ' each iteration. Take whatever the user enters (unknown length) and read it into a character array, dynamically allocating the size of the array if necessary. The user-entered line will end at...

Program blocks after input

c,arrays,gcc,scanf
This code blocks immediately after scanf():  int main(int argc, char *argv[]) { puts("Algorithms test kit"); long input_size; FILE *output=fopen("output.txt","w+"); do { printf("Enter sample size(0 goes on to next test) > "); scanf (" %li ",&input_size); printf ("#"); if (input_size==0) break; int64_t *data=sorting_prepare_data(input_size); int64_t *bsort_copy=calloc(input_size,8); int64_t *qsort_copy=calloc(input_size,8); memcpy(bsort_copy,data,input_size*8); bubblesort(bsort_copy,input_size);...

Why does inputting an unexpected value type via scanf() cause this program to enter an infinite loop

c,types,buffer,scanf
Consider the following code snippet: int n; int a[100]; int main() { printf("\nThis program will sort a given list of between 1 and 100 integers.\n\n"); int ready = 0; while(!ready) { printf("How many integers are in your list? "); scanf("%d",&n); if(n>100) { printf("\n\nError:\tToo many integers.\n\tThis program can only handle up...

How to scanf to just one dimension of a multidimensional array in C?

c,arrays,loops,multidimensional-array,scanf
Suppose I have some C code like this, which declares a small multidimensional array: #include <stdio.h> #include <conio.h> int main(void) { int mat[5][2] = { {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0} } do scanf("%i", &mat[][]); while (getchar() != '\n'); return 0; } and I want to...

Difference between fgets and gets

c,scanf,fgets,gets
What is the difference between fgets() and gets()? I am trying break my loop when the user hits just "enter". It's working well with gets(), but I don't want to use gets(). I tried with fgets() and scanf() but I don't have the same results as with gets(). fgets() breaks...

C Programming: How to check if user has entered numeric values only in the following expression?

c,validation,date,exception,scanf
I am taking a certain date as an input from user in following format: mm/dd/yyyy. How can I make certain that the user is entering numeric values only and if not then prompt him again to enter a valid date. I am already checking if a date is valid or...

program using the rand () function

c,random,scanf,modulo
I want to make a simple program in which the rand() function generates a random number out of 1,2,3 and the user is asked to predict the number. if the user predicts the number correctly then he wins otherwise he looses. Here's the program- #include <stdio.h> #include <stdlib.h> int main()...