%n not working in printf - c

I have a problem, %n in printf doesn't work, i'm using Dev-Cpp 5.3.0.4 on win7
#include<stdio.h>
int main(void)
{
int n;
char *x;
gets(x);
printf("\n%s%n\n",x,&n);
printf("n: %d\n",n);
return 0;
}
output:
hello how are you?
hello how are you?n: 2046
--------------------------------
Process exited with return value 0
Press any key to continue . . .
why? how can i solve? thanks in advance ;)

Have a look at the printf manpage:
n The number of characters written so far is stored into the integer indicated by the int
* (or variant) pointer argument. No argument is converted.
So, you'll have to pass a pointer to an int. Also, as Xavier Holt pointed out, you'll have to use a valid buffer to read into. Try this:
#include <stdio.h>
int main(void)
{
int n;
char x[1000];
fgets(x, 1000, stdin);
printf("\n%s%n\n",x,&n);
printf("n: %d\n",n);
return 0;
}
This code works for me.

You need to pass a pointer to n.

The argument to n needs to be a pointer to a signed int, not a singed int.

That's not how to use the "%n" specifier.
See the C99 Standard.
n
The argument shall be a pointer to signed integer into which is written the number of characters written to the output stream so far by this call to fprintf. No argument is converted, but one is consumed. If the conversion specification includes any flags, a field width, or a precision, the behavior is undefined.
Also you need some place to store the input (hint: initialize x)

Related

Code blocks output console has stopped working

Whenever i declare a varible as char and scan it as string "%s" my output console crashes. Here is the code
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
char a[20];
int i;
printf("Enter a name ");
scanf("%s",&a);
for(i=0;i<strlen(a);i++)
{
a[i] = toupper(a[i]);
i++;
printf("%s\n",toupper(a[i]));
}
return 0;
}
The second i++; inside the for loop body may cause the index to point off-by-one then, printf("%s\n",toupper(a[i])); will be out of bound access which invokes undefined behavior.
You can remove the i++ from inside the loop body.
Next, toupper(a[i]) returns an int, which is invalid for %s format specifier, which again invokes UB.
That said,
to prevent buffer overflow from excessive long input, it's best to limit the input length with scanf(),
You don't need to pass the address of an array, just the array name will be sufficient
So, overall, you should write
scanf("%19s",a);
You have two problems in the loop where you use toupper and print.
The first is that you increment the variable i twice in the loop.
The second problem is the printf:
printf("%s\n",toupper(a[i]));
Here you ask printf to print a string, but as argument you give it a single character (actually an int, toupper returns an int). Use the "%c" format specifier to print a single character.
By the way, you don't need to call toupper when printing, as the character should already be in upper-case because of the previous assignment.
Your printing loop is mis-behaving and giving you undefined behavior:
printf("%s\n",toupper(a[i]));
is passing toupper(a[i]) to printf()'s %s format specifier, which requires a char * not a plain char. That triggers undefined behavior.
There's no point in printing each character one by one, instead convert the entire string to upper case, then print it once:
for(i = 0; a[i] != '\0'; ++i)
{
a[i] = (char) toupper((unsigned char) a[i]);
}
printf("%s\n", a);
The casts around toupper() are sometimes needed since it takes and returns int, and you want to be a bit careful about when converting to/from characters.
Notice that I factored out the call to strlen(), this might be a bit "too clever" but it's how I would expect this code to be written. If we're going to loop over the characters, there's no need to compute the length separately.

Length modifier vs conversion specifier in C

I'm new to C and I'm struggling to understand the difference between the two. Can someone use an example with both? Please correct my logic if I'm wrong but this is the way I understand the following:
int a = 10;
printf("%d\n", a);
The purpose of %d is to notify the compiler that the variable we want to print is of int type. At least, that's the way I've been thinking of it so far. Thank you.
In a format string like %ld, the letter l would be the length modifier, which indicates to the standard library function (not the compiler) that you want the associated argument to be interpreted as a long int. There's a handy chart showing the standard interpretations made by various length/conversion character combinations here on cplusplus.com.
The compiler knows the types of all your variables at compile time, but the printf function doesn't have a way to determine the types of arguments at run time because of how variadic functions work. You can experiment for yourself and see how different combinations of length modifiers and conversion specifiers can yield completely different results for the same data passed to printf.
The *printf() family of functions take variable number of arguments, so you need to pass a format string with specifiers that let the function know the type of the currently parsed argument.
A simple example would be like this1
#include <stdio.h>
#include <stdarg.h>
int xprintf(const char *format, ...)
{
char chr;
int count;
va_list va;
count = 0;
va_start(va, format);
while ((chr = *format++) != '\0')
{
if ((chr == '%') && ((chr = *format++) == 'd'))
{
int argument;
argument = va_arg(va, int);
count += printf("%d", argument);
}
else
{
fputc(chr, stdout);
count += 1;
}
}
return count;
}
int
main(void)
{
xprintf("example %d\n", 4);
return 0;
}
The compiler does not need to know anything about it, but somtimes it does and it helps you know when you pass the wrong argument type by mistake, but code with wrong, extra, less arguments can compile and then the behavior of the program can't be specified in those cases.
1Notice that I've used the standard printf() as an auxiliary function to print the integer.
The conversion specification tells printf both the type of the argument and how you want to format the output for it. The length modifier is a part of the conversion specification, and it gives printf additional type information for the corresponding argument.
printf is a variadic function, which means arguments of certain types are promoted to a more limited set of types; arguments of type char and short are promoted to int, arguments of type float are promoted to double, etc. The length modifier helps you communicate the original type to printf, so it will properly convert the promoted argument back to the original type.
So, examples:
int aRegularInt = 64;
short aShortInt = 64;
char aReallyShortInt = 64;
printf( "aRegularInt = %d\n", aRegularInt );
printf( "aShortInt = %hd\n", aShortInt );
printf( "aReallyShortInt = %hhd\n", aReallyShortInt );
printy( "aReallyShortInt = %c\n", aReallyShortInt );
The conversion specification %d indicates that the argument has type int and that the output should be a string of decimal digits with a leading - for negative values. There is no length modifier.
The conversion specification %hd indicates that the argument has type short int. The output is the same as above. h is the length modifier.
The conversion specification %hhd indicates that the argument has type char. The output is the same as above. In this case the length modifier is hh.
The conversion specification %c indicates that the argument has type int, and that the output should be the glyph corresponding to that character code (in ASCII, the character for code 64 is #).

Return value from the function varies in c

I wrote a program to fetch all the phone numbers from a file which has other text like at commands and other error from other child process. Here when I try to convert the string to integer using a user-defined function I facing the problem. The converted value stored in the function is not properly returned to main program, instead its returning some unusual and it seems to be the same for every execution. Its surprising me. Can someone advice me.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char lic[128];
unsigned long long sum=0ULL;
unsigned long long stringtoint(char str[])
{
int i=0;
sum=0;
if(str[strlen(str)]!='\0')
return -1;
//puts("Im in function");
while(str[i]!='\0'){
//printf("- %c -\n",str[i]);
if(str[i] >= 48 && str[i] <= 57){
sum = sum*10 + (str[i] - 48);
//printf("%c and %llu\n",str[i],sum);
}
i++;
}
if(sum>0)
printf("\nIn function passed string is %s and integer value is %llu\n",str,sum);
return sum;
}
FILE *file;
int main(){
//long long int inte;
int64_t inte; file = fopen("receive","r");
if(file!=NULL)
while(fscanf(file,"%s",lic)!=EOF){
inte = 0;
inte=stringtoint(lic);
if(inte !=0){
printf("In Main %llu is the value of the string %s",inte,lic);
if(inte==sum)
printf("\n%llu and %llu are same\n",inte,sum);
}
}
printf("\n");
fclose(file);
return 0;
}
The result I was getting for this program was given below.
In function passed string is 8939095683 and integer value is 8939095683
In Main 349161091 is the value of the string 8939095683
shameerariff#shameerariff-Satellite-L450:~/Workinffolder/ivr/IVRReporting$ ./datadecoder
In function passed string is 8939095683 and integer value is 8939095683
In Main 349161091 is the value of the string 8939095683
shameerariff#shameerariff-Satellite-L450:~/Workinffolder/ivr/IVRReporting$ ./datadecoder
In function passed string is 8939095683 and integer value is 8939095683
In Main 349161091 is the value of the string 8939095683
Your valuable advice are needed, Thank you in advance for your support.
Point 1. You need to change
int stringtoint(char str[])
to
unsigned long long stringtoint(char str[])
Point 2. %lld is not the correct format specifier for unsigned long long. Use %llu
Can someone advice me.
Yes. Don't write your own function, but use the atoi function available in the C standard library if you really want to operate on char arrays, or use the stoi function to work on std::string, or use any C++ iostream to read ints from your strings. With the latter, you can basically just use the file stream you can directly get when opening a ifstream with C++'s standard library.
EDIT: I should mention you shouldn't use atoi/stoi, but atoll/stroul to actually reflect the fact that your numbers could be bigger than whatint can hold.
Also, phone numbers are not integers. In many countries, city area codes start with 0, which you can't represent in any numeric type. In fact, telephone numbers are not numbers, but sequences of digits, if you ask me.

What happens when using scanf("%d", &c) while c is a char?

the code is like this:
char c;
scanf("%d", &c);
inputting 3...
My guess is that when 3 is inputted, it is as type int;
and then type-demoted to char and assigned to c;
I print the value of c in specifier %d yielding 3, seems to be as expected;
but printing the value of c with specifier %c yields --a blank-- on the terminal;this is one question...(1);
to test more I furthermore declare a variable ch with type char and initialized it like this:
char ch = 1;
and the test is like this:
(i&j)? printf("yes") : printf("no");
and the result is "no"
I print out the value of i&j, and it is 0
but 1&3 should be 1? this is another question....(2);
my question is (1) and (2)
You're actually invoking undefined behavior doing that.
By using the format string %d, you're telling scanf to expect an int* as a parameter and you're passing it a pointer to a single character. Remember that scanf has no further type information on what you're passing it than what you're putting in the format string.
This will result in scanf attempting to write an int sized value to memory at an address that points to a char sized reservation, potentially (and for most architectures) writing out of bounds.
After invoking UB, all bets are off on your further calculations.
Suppose that scanf() were not a varargs-function, but a plain ordinary function taking a pointer-to-int as the 2nd argument:
int noscanf(char *format, int *ptr)
{
*ptr = 42;
return 1;
}
int main(void)
{
char ch;
int rc;
// This should *at least* give a warning ...
rc = noscanf("Haha!" , &ch);
return 0;
}
Now, scanf() is a varargs function. The only way for scanf() to determine the type of the (pointer) arguments is by inspecting the format string. And a %d means : the next argument is supposed to be a pointer to int. So scanf can happily write sizeof(int) bytes to *ptr.
I can't see a variable jthere. So i&j will be 0. And yes, if i == 1 and j == 3 then i & j == 1.
(i&j)? printf("yes") : printf("no");
statement gives the output yes,for i=1 and j=3.
And for (1) question ASCII 3 is for STX char which is not printable.

How Do I Convert an Array of Characters To Integers?

I am Just a begineer in C Programming. While solving a programming assignement I came across the need to convert an array of unsigned char to integer.
For Example:
unsigned char x[]="567";
unsigned char y[]="94";
Now I have to add the integer values in both x and y. That is:
int sum=661;
What is the simplest way to do this?
You're looking for atoi() .
You have at least two options if you use standard library. The first is atoi() function from stdlib.h and second is sscanf()function from stdio.h.
Here are examples:
atoi()
char number_string[] = "47";
int number;
number = atoi(number_string);
sscanf()
char number_string[] = "47";
int number;
int return;
return = sscanf(number_string, "%d", &number);
/* it would be good idea to check the return value here */
sscanf() gives you a better error handling. Return value of sscanf() determines how many items were succesfully read (how many variables were filled). If there was an input failure, EOF is returned.
atoi() returns 0 if no valid conversion could be performed.

Resources