You'd want to use: #include <stdlib.h> /* ... */ int *arr; scanf("%d", &n); arr = malloc(sizeof(int) * n); This way, arr gets dynamically allocated at runtime, so it can be of any size depending on the input n. What you were originally doing (i.e. declaring arr[n] after recieving n via...
The code is behaving correctly. Indeed, scanf is declared int scanf(const char *format, ...); Luckily, your format does not contain any % for which there would be no correspondence in ..., which would invoke UB. Further, format is a string literal which allows the compiler to go through it ensuring...
c,concurrency,process,signals,scanf
Let me see if I got it right, your problem is that child process is failing to read stdin, right? You may use fscanf(stdin, stringa); I've tested with a simple example and worked (just changing your scanf by fscanf). Let me know if that was your problem....
Your loops should be for (count=0;count<SIZE;count++) Array indexing is 0 based in C. Since you have a whitespace chatacter (\n) in scanf() call, it waits for you input a non-whitespace character to complete each call. Remove the \n: for (count=0;count<SIZE;count++){ scanf("%d",&myArray[count]); } ...
Judging by this statment: 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 I assume you want this: first initialize sumDice to 0: int sumDice=0; then, in every for loop...
When the format string in scanf_s contains %s or %S, the function expects another parameter that indicates the size of the string. See https://msdn.microsoft.com/en-us/library/w40768et.aspx. Instead of scanf_s("%[^\n]",std.studentNumber); you'll need to use: scanf_s("%[^\n]",std.studentNumber, sizeof(std.studentNumber)); Similar changes need to be to the other calls to the function....
isdigit() takes the ascii value of a character and returns 0 if it's not a digit and non-0 if it is. You are passing to it an integer value which is not necessarily an ascii value, you don't need to check if it's a digit since you read it with...
Because 215- 15 can only match one number: 215. As soon as scanf() reads a -, it stops processing the first match since - can't possibly be a digit of the current number, so num1 is matched with 215. Then, no more numbers can match, because you are left with...
assumes sizeof (int) and sizeof (int*) are the same m=(int**)malloc(n*sizeof(int)); Try this m = malloc(n * sizeof *m); ...
As per C11 standard, Chapter §6.3.2.3 An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation. So, the compiler will allow this,...
first issue: Try to read to string and then translate the string to integer by using sscanf, if it is not equal to "end". (compare by strcmp not by ==). second issue: when you read numbers, you never reach to c++. the continue make it skip it. for example, you...
sscanf takes first argument of type const char *.You are passing the first argument as FILE *. You can use: fscanf OR fgets with sscanf ...
int check = scanf("%d", &x); does not consume the "input is a character not a number", leaving that input in stdin for the next input function. Since the next input function is check = scanf("%d", &x);, it does not consume the offending data and so the cycle repeats. Code needs...
Apparently you have a char * and you are passing it's address, which is wrong, scanf() wants a char pointer for each "%s" specifier, and the fix for your code is to use char string[10]; scanf("%s", string); the array automatically becomes a char pointer when passed to scanf() like above,...
Scanning with %i and values with a leading zero are assumed to be octal. 08 and 09 are not octal values. Use %d instead as leading zero's are ignored and values are in base 10. For the sscanf you might try this. It will scan the five items present in...
c,arrays,user-input,scanf,dynamic-memory-allocation
First of all, scanf format strings do not use regular expressions, so I don't think something close to what you want will work. As for the error you get, according to my trusty manual, the %a conversion flag is for floating point numbers, but it only works on C99 (and...
Two advices when using scanf (especially for numbers): 1) use fflush(stdin); before each call of scanf; 2) check the result of unputs - is number received or not? For example, if you cannot work without correct input: do{ printf("Please, enter number: "); fflush(stdin); } while( 1 == scanf("%d", &number)); ...
Because the scanf function will only extract the input if it's correct. If the input is not correct, the input will still be in the input buffer when the loop iterates, and the next call to scanf will read the exact same input. You might want to either use the...
The problem is are with Point 1: if(gender == "M") it should be if(gender == 'M') Reason: "M" represents a string, 'M' represents a char. Point 2: scanf("&s", gender); should be scanf(" %c", &gender); Reason: Need to use proper signature of scanf(). %c is the format specifier for scanning a...
So you had a scanf("%f'\n'%f'\n'%s",&lati,&longi,info) in your code. When you break this code up: %f - expect a float ' - expect a literal ' in the input \n - expect a line break ' - expect a literal ' in the input ... and so on. \n is a...
c,arrays,floating-point,printf,scanf
Just change this: float price[10000]; to this: float price; Because you use it as a single variable and not as an array...
You can use sscanf() to advance through a buffer read by fgets() %n will receive the number of characters used by the scan. Adding used to the offset will advance the scan through the buffer. int offset = 0; int used = 0; char line[1000]; char item[200]; fgets ( line,...
When you enter the data in the first read of this scanf: scanf("%c", &ms); A newline character remains in the keyboard. To solve this put a space in your second scanf: scanf(" %c",&s); This is to consume any trailing character in the stdin that might have been left by previous...
c,arrays,function,scanf,elements
The problem is that you are iterating from 1 and you should iterate from 0, in the inner_product() function for( i=1; i<count; i++) { /* ^ this should be 0 */ also, don't use global variables specially because you got the rest of it right, you are passing the arrays...
c,arrays,loops,multidimensional-array,scanf
You want something like this. int i=0; do{ scanf("%d", &mat[i][1]); i++; }while (getchar() != '\n'); ...
Because you have an operator precendence problem here chr = getchar() != EOF this is evaluated as chr = (getchar() != EOF) because the != operator has higher precendence than the assignment operator =, so you just need to add parentheses like this (chr = getchar()) != EOF Tip: Check...
c,string,struct,user-input,scanf
You can specify complex formats using scanf, like: scanf("%79[^,],%c,%d,%d", apple.item, &apple.letter, &apple.x, &apple.y); %79[^,] means scan anything that is not a comma character, up to 79 characters. Note that this does no error handling if the user enters a poorly formatted string, like "aaa;b;1;2". For that, you'll need to write...
Substitute printf("%d",&n); with scanf("%d",&n); printf Writes the C string pointed by format to the standard output (stdout) scanf Reads data from stdin In your code you are printing n, that is not initialized, that a random number is printed out after "Enter numbers to be stored in file" string....
In your case, scanf("%d ", &a[i]); after scanning an integer, scanf() needs to match the white space, and any number of white space until a non-white space character is required to complete the match. So, for the first time, the second input is the non-white space, which terminates the scan,...
Try this if (scanf_s("%99s", name, _countof(name)) == 1) printf("Your Name is: %s", name); Two things scanf_s() is a buffer overflow safe function, and it expects a length argument for "%s" specifier. You should only proceed to printf() if you actually succeeded scannig the value, for which the check (scanf(...) ==...
Why spend time converting the answer when scanf() can do it for you? #include <stdio.h> int main(void) { float height_in_inches; printf("Enter your height in inches: "); if (scanf("%f", &height_in_inches) == 1) { float height_in_cm = height_in_inches * 2.54; printf("You are %.2f inches or %.2f centimetres tall.\n", height_in_inches, height_in_cm); } else...
You basically have three options. Option I Redirect stdin/stdout (those are the streams scanf reads from and printf writes to) in the console, when you start your program. On both Windows and Linux, this can be done like so: < in.txt - redirects all reads from stdin to in.txt >...
Change scanf('%d', &row); to scanf("%d", &row); '%d' is a multicharacter literal which is of type int. "%d" on the other hand is a string literal, which is compatible with the const char * as expected by scanf first argument. If you pass single quoted %d, compiler would try to do...
scanf is just reading from its input stream. If the input stream is a pipe, and the other end of that pipe is associated with a tty (which is usually the case if you are interactively entering data by pressing keys on a keyboard), scanf will return as soon as...
if (array[i] == '5') You're checking whether array[i] is equal to the ASCII value of the character '5'. Remove the '' to make it compare against the integer 5....
You are assigning the returned value from scanf_s() to the variable n, that means that the program will print 1 in case a successful read happened. What you should do is int numberOfItemsMatched; int readValue; numberOfItemsMatched = scanf_s("%d", &readValue); if (numberOfItemsMatched == 1) printf("%d\n", readValue); I hope the variable names...
Your scanf to read in op is invalid. op is a single char, so you should read with scanf("%c",&op); Not scanf("%s",&op); ...
From your tags, I'm guessing you're using printf(). Simply leave out the "\n" character, which means "newline.". In other words. printf("> "); printf("text\n"); This will print: > text ...
For var4, you declare it as unsigned char, but read it using a %d format specifier, which invokes undefined behavior. I would recommend using %hhu as the format specifier for that field, if your compiler supports it. Or you could declare var4 as an int, and then assign it to...
You have a space in your format after the second %i. scanf will read extra data to match the space. Remove the space and it should work as you expected.
c,input,printf,scanf,format-specifiers
TL;DR; - A # after a % sign in the format string of scanf() function is wrong code. Explanation: The # here is a flag character, which is allowed in fprintf() and family, not in fscanf() and family. In case of your code, the presence of # after % is...
fflush(stdin); is undefined behaviour in standard C. To flush the newline character, you could simply use getchar() instead. printf("\nEnter staff name \t> "); getchar(); scanf("%[^\n]s", staff_name2); I would also use fgets() instead of scanf to read a line and trim the newline if necessary, which offers better control over invalid...
Here is your problem. char gender; scanf(" %s",&gender); gender is a char. That is, it only has memory for a 1 byte character. But you are using it as a string. You probably have the same problem for name1 since you are using & for that as well but can't...
Most OSes buffer keyboard input so that they can process backspaces properly -- the OS keeps input in a buffer and only gives it to the program when Enter is hit. Most OSes also provide ways to control this, but the way is different for different OSes. On POSIX systems,...
To add to the above answers ... look at this example: int number = 5; printf(" %d\n", number); // Prints value of 'number'. printf(" %p\n", &number); // Prints address of 'number'. printf(" %d\n", *(&number)); // Prints value at address of 'number' ... ...
Drop gets() and scanf(). Create a helper function to handle and qualify user input. // Helper function that strips off _potential_ \n char *read1line(const char * prompt, char *dest, sizeof size) { fputs(prompt, stdout); char buf[100]; *dest = '\0'; if (fgets(buf, sizeof buf, stdin) == NULL) { return NULL; //...
The biggest problem with your program is that scanf will not read an EOF into a variable. However, fixing just this problem is not going to make your program entirely correct, because there are other issues in your code: Your code repeats itself - when possible, you should unify the...
Some issues with your code: Point 1: scanf("%d\n",&x); should be scanf("%d",&x); Point 2: for(i=0;i<1;i++) this for loop is practically useless. It only iterates one. either use a longer counter, or get rid of the loop. Point 3: It's better to provide a unique seed to your PRNG. You may want...
You need to use int c; while((c=getchar()) != '\n' && c != EOF); at the end of the while loop in order to clear/flush the standard input stream(stdin). Why? The answer can be seen below: The scanf with the format string(" (%d,%d)\n") you have requires the user to type An...
You can change your code fscanf(fp,"%4s %7s %9s %16[^\n] %11[^\n] %2s %5s",... to the style fscanf(fp,"%4s;%7[^;];%10[^;];...... to have the ;s as a part of the format string. Then it won't be considered as a part of the string input. Note: The above method is just a workaround and will break...
#include <windows.h> #include <stdio.h> int main(void){ int num = 0; DWORD waitCode; printf("input number : "); //wait console input 10,000 Millisecond waitCode = WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE) , 10*1000); switch(waitCode){ case WAIT_TIMEOUT: fprintf(stderr, "\n10 seconds are over no more input\n"); return -1; case WAIT_OBJECT_0://normal status scanf("%d", &num);//input from stdin buffer if(num)//not zero printf("input...
Point 1 Do not use fflush( stdin );, it is undefined behaviour. Related: from C11 standard docmunet, chapter 7.21.5.2, (emphasis mine) int fflush(FILE *stream); If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten...
Remove the '\n' left by the previous scanf() like this scanf(" %c %x", &read_size, &address); /* ^ tell scanf to skip white spaces with the %c specifier */ also do not ignore scanf()'s return value, it might cause very weird things in case it fails and you fail to detect...
Use fgets() to get your input into a string and sscanf() to evaluate it. Since you just want what the user entered, you don't really need sscanf() in this case anyway See this post...
Point 1: Use strcmp() for string comparison, not == operator. Point 2: Anyways, for an array of char yourchoice[40]="";, using yourchoice[40] is out of bounds which in turn invokes undefined behaviour. Array index in C starts from 0. Point 3: printf() does not need to have a pointer to data...
scanf() with format specifier %s scans the input until a space is encountered and in your case what you are seeing is undefined behavior your array can hold 10 char's but you are writing into array out of bounds and still getting desired answer which is not guaranteed and might...
As pointed out by @SouravGhosh, you can limit your scanf with "%3s", but the problem is still there if you don't flush stdin on each iteration, you can do it in this way: printf("\n enter the names \n"); for(i = 0; i < 3; i++) { int c; scanf("%3s", name[i]);...
It seems the formatting is wrong, you want to read the colon and there are no commas. Try this: scanf("%m[^':']:%m[^':']", &str, &i); Hope this helps....
c,arrays,algorithm,scanf,getchar
You are trying to read integers as characters so once read you need to convert it to integers. Read the line to a buffer using fgets() then parse the input buffer to get integers. Store the integers to the array. The code looks like char buf[300]; int a[5],i=0; fgets(buf,sizeof(buf),stdin);...
Most scanf() field descriptors implicitly cause leading whitespace to be skipped and expect the field to be whitespace-terminated. To scan a string that may contain whitespace, however, you can use the %[] field descriptor with an appropriate scan set. Thus, you might scan sequence of lines following the pattern you...
c,arrays,string,segmentation-fault,scanf
In your code, char * n = ""; makes n point to a string literal which is usually placed in read-only memory area, so cannot be modified. Hence, n cannot be used to scan another input. What you want, is either of below a char array, like char n[128] =...
Have you considered doing this using a combination of scanf(), fgets() and strtok()? For example, you can use scanf() to simple query the number of inputs expected. Then use a loop around `strtok() to tokenize user's input: int main() { char line[1024]; char *token = {0}; char delim[]={" \r\n\t"}; long...
You have run into a bug of Microsoft's C/C++ runtime library, cf. http://mfctips.com/tag/format/ or https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63417 (which reports this bug for gcc under mingw, which links against the Microsft libs). "%hhd" just doesn't work; you must program around it (which isn't too hard, but sad). I am not aware of a...
In your code, printf("%s", s[i]); is wrong. Change it to printf("%c", s[i]); as, you're trying to print a char value. The conversion specifier for a char is %c. Note: Always remember, using wrong conversion specifier will lead to undefined behaviour. Also, while scan()-ing with %s, you cannot read the whole...
From the C11 standard document, chapter §7.21.6.2, Paragraph 12, conversion specifiers, (emphasis mine) [ Matches a nonempty sequence of characters from a set of expected characters (the scanset). .... The conversion specifier includes all subsequent characters in the format string, up to and including the matching right bracket (]). The...
Let us look at this step by step: "... read a line with scanf("%[^\n]");". scanf("%[^\n]", buf) does not read a line. It almost does - sometimes. "%[^\n]" directs scanf() to read any number of non-'\n' char until one is encountered (that '\n' is then put back into stdin) or EOF...
.2%d is not a valid format string. For a start, the % has to come first. In addition, if you're after a floating point value, d is not the right character - it's for integral values. You should be using something like %f (you don't need width or precision modifiers)....
The reason printf is outputting a newline is that you have one in your string. fgets is not "adding" a newline --- it is simply reading it from the input as well. Reading for fgets stops just after the newline (if any). Excerpt from the manpage, emphasis mine: The fgets()...
scanf returns the number of items scanned. In this case it would be 2 instead of 1. Here a return of 1 would indicate a problem during the scan. The %m specifier allocates memory to the pointers. Using a single pair of pointers, they should be freed in eadh iteration...
In your code, change scanf("%lf \n", &radius); to scanf("%lf", &radius); Otherwise, with a format string having whitespace, scanf() will behave as below (quoted from C11, chapter §7.21.6.2, paragraph 5) A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or...
I tried you code and manage to reproduce the weird behaviour. If you remove the " " around "%li" it doesn't block anymore. The problems were the blank spaces because scanf was expecting the input to match the empty space as well. From the scanf documentation: All conversions are introduced...
Basic answer There isn't an analog to the printf() format specifier * in scanf(). In The Practice of Programming, Kernighan and Pike recommend using snprintf() to create the format string: size_t sz = 64; char format[32]; snprintf(format, sizeof(format), "%%%zus", sz); if (scanf(format, buffer) != 1) { …oops… } Extra information...
c,function,return,printf,scanf
In the following function: int GetPositiveInt(void) { int n; do { printf("Enter a positive number : "); scanf("%d",&n); }while(n<=0); } the function is expected to return an int value, whereas there is no return statement. You probably wanted to return the value of n. This can be achieved by adding...
Code has input and output issues; char home[15]="HOME"; ... printf("Do you want to enter teams' names?\n1-Yes\n2-No\n:>>"); scanf("%d",&choice1); ... printf("\nPlease enter HOME team's name(max 15 characters including space)\n:>>"); scanf(" %[^\n]s",&home); ... Input1: The 's' in " %[^\n]s" is certainly not needed. 's' is not part of the "%[^\n]" format specifier. Input2:...
Ok, the original idea does not seem to work, so another try: scanf("%d",&s.rollNumber); printf("Name: "); fgets(s.name, 20, stdin); /* capture the new line */ fgets(s.name, 20, stdin); Original idea: Simply tell scanf to also capture the newline: scanf("%d\n",&s[i].rollNumber); ...
c,validation,date,exception,scanf
There are a couple of issues. If using scanf check its return. In addition to the numeric validity checks, you also have the issue of needing to flush the input buffer in the event something other than an integer is entered by the user. While there are several ways to...
The trick is to put ']' as the first character in the pattern: scanf(" %80[^]]", &buf); ...
c,printf,structure,scanf,fflush
The C11 standard explains how %c works: §7.21.6.2/8 Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier. As such, the linefeed produced by the enter key is consumed by %c. You can fix this by adding a space...
char c, implies scanf("%c", &c) can only read a single character into char variable c. Hence input 197 will read as 1 in to c, making logical && true. Look at this compilation
c,char,segmentation-fault,user-input,scanf
I'm not saying that it cannot be done using scanf(), but IMHO, that's not the best way to do it. Instead, use fgets() to read the whole like, use strtok() to tokenize the input and then, based on the first token value, iterate over the input string as required. A...
On the 2nd time through the loop, scanf("%c",&penal1); is scanning in the '\n' from the previous user input. Add a preceding space like code used in other places to consume all preceding white-space. scanf(" %c",&penal1); // added space. Code should check not only for 'O' and 'o', but 'X' and...
If you read e.g. this scanf reference, you will see that the "%[" format is for reading a string which of course includes writing the string terminator character. Since you only provide a single character to store the read string, the scanf function will always write out of bounds and...
scanf doesn't support regular expressions. It supports strings of a given set of characters. When your format contains %[^';'] it matches any sequence of one or more characters except ' and ;. When your format contains a comma (,) it matches a comma. So when you say: sscanf(multiple, "%[^';'], %[^';'],...
c,file-io,whitespace,scanf,fscanf
To your first question: No, white space does not need to be considered in fscanf(). To your second question: Neither of these will work. You seem to be misunderstanding how information is stored in a computer. In the program, an integer is 32 bits (4 bytes), so sizeof(int) will always...
c,pointers,segmentation-fault,scanf
In your code, stack* st; st->top=-1; you're using st uninitialized which in turn invokes undefined behaviour. You need to allocate memory to st before using it. Try something like stack* st = malloc(sizeof*st); //also, check for malloc success That said, Please see why not to cast the return value of...
c,while-loop,char,scanf,getchar
That's because scanf() left the trailing newline in input. I suggest replacing this: ch = getchar(); With: scanf(" %c", &ch); Note the leading space in the format string. It is needed to force scanf() to ignore every whitespace character until a non-whitespace is read. This is generally more robust than...
You can do something like that: for(i=0;a[i]<10000;i++) { // chack that input correct if((scanf("%d",&a[i])==1) { count++; } else // if input is incorrect { // read first letter int c = getchar(); if( c == 'q' ) { break; // stop the loop } // clean the input buffer while(...
Your scanf is perfect. I think that your mistake is the loop for from esPrimo. Actually you have an infinite loop, because sqrt(n) has always the same value and it isn't a boolean expression. Change your loop: for(divisor = 2; sqrt(n); divisor++) { if(n <= 0) { return falso; }...
The scanf command does not consume the Enter key that you pressed after entering y. So the getchar() happily consumes it. One solution is to consume the rest of the input line after reading y; the code for that looks like: int ch; while ( (ch = getchar()) != '\n'...
You must use "%llx" for both scanf format and printf. See the manual page for additional details.
When scanf() fails, the argument is not automatically initialized, and uninitialized values could be any value, so it might be less than 2 or greater than 64 no one knows. Try this int initialBase; /* some default value would be good. */ initialBase = 2; do { printf("Initial base: ");...