C- leading zero without printf [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Ethernet starter kit(PIC32MX9795F512L)
language: C
MPLAB IDE 8.92
Compiler: XC32 v1.3
Hello i want to add leading zeros to my variables. At the end i want to use the in an array.
For example: c=10*a+b. When c=5 it should be 05. I cant use any printf function or am I wrong?

You can use printf() to simply print a formatted number to standard output:
int c = 5;
fprintf(stdout, "c [%02d]\n", c);
If you can't use printf(), another option is to store the padded value in a char * or string. You can instead use sprintf() to write the formatted string to a char * buffer.
For example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[]) {
{
char* c_str = NULL;
int c_int = 5;
int c_str_length = 3; /* two bytes for "0", "5", and one byte for the nul terminator */
c_str = malloc(c_str_length);
if (!c_str) {
fprintf(stderr, "Error: Could not allocate space for string!\n");
return EXIT_FAILURE;
}
int n = sprintf(c_str, "%02d", c_int);
if (n != c_str_length) {
fprintf(stderr, "Error: Something went wrong in writing the formatted string!\n");
free(c_str);
return EXIT_FAILURE;
}
fprintf(stdout, "c_str: [%s]\n", c_str);
free(c_str);
return EXIT_SUCCESS;
}
If you go this route, you can see how you could do some error checking along the way. You'll need to think about string length (hint: log10()), or use a static char [] array in place of a char * of sufficiently long length.

It is quite easy to add a leading zero, provided you take care of negative values too. You said you want to write to an array, so I used sprintf but if you want to output directly, you can use printf in a similar way.
char cstr[24];
int c = 10 * a + b;
if (c > 0) {
sprintf(cstr, "0%d", c);
} else if (c < 0) {
sprintf(cstr, "-0%d", -c);
} else {
//sprintf(cstr, "00");
sprintf(cstr, "0"); // depending on your needs
}

Related

How do I check for a specific character after a user inputed a string? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am a new developer to C and I am trying to make a password detector and I am trying to code something that reads the users password and checks if it has a "!" in it. Yet, I cant seem to get it to work. the output of "int special" always equals 0.
The code:
#include <stdio.h>
#include <string.h>
void main() {
// check for special characters
// check for length of password
char password[30];
int length;
int len = 15;
printf("Dear user please enter a password:\n ");
scanf_s("%s", &password, 30);
length = strlen(password);
if (length < len) {
printf("invalid password (password must be 15 - 30 characters)");
exit();
}
int special = 0;
if (strchr(password, "!") != NULL)
{
special = 1;
}
printf("%d", special);
}
The basic idea of the program is correct, but a couple of fixes are needed to make it work and standard compliant:
The typical signature for the main function, using no parameters, is int main(void). See the C standard document for more information.
Include stdlib.h for the exit(..) function. This function needs an argument, and since it is used to exit with failure, the best choice is EXIT_FAILURE as defined in stdlib.h. Since exit(..) is called in the main function, another option is to simply return EXIT_FAILURE.
The scanf_s function is a bit of a special case: __STDC_WANT_LIB_EXT1__ needs to be defined as the integer constant 1 before stdio.h is included. See here for more information. Note that providing an implementation for this function is optional in C, so it is not the best choice for portability. Here, fgets is a better alternative.
The function scanf_s needs a char array to write to and password has exactly that type. Therefore, the "address of" operator (&) shouldn't be used here.
Then function strchr needs a char argument ('!'), not a string literal ("!"). See here for the exact function prototype.
The code will all fixes applied:
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
// check for special characters
// check for length of password
char password[30];
int length;
int len = 15;
printf("Dear user please enter a password:\n");
scanf_s("%s", password, 30);
length = strlen(password);
if (length < len) {
printf("invalid password (password must be 15 - 30 characters)\n");
exit(EXIT_FAILURE);
}
int special = 0;
if (strchr(password, '!') != NULL)
{
special = 1;
}
printf("%d\n", special);
}
A few additional suggestions:
Use a macro for the constant length to give it a name, and to define it once and reuse it multiple times.
Use the size_t type for lengths. This is also the type that is returned by strlen.
Declare variables as close as possible to where these are first used.
Store the result of strchr directly into a boolean value. To use the bool type, include stdbool.h.
The improved code:
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PASSWORD_LENGTH_MAX 30U
int main(void) {
char password[PASSWORD_LENGTH_MAX];
printf("Dear user please enter a password:\n");
scanf_s("%s", password, PASSWORD_LENGTH_MAX);
size_t length_min = 15U;
size_t length = strlen(password);
if (length < length_min) {
printf("Invalid password (password must be 15 - 30 characters)\n");
exit(EXIT_FAILURE);
}
bool contains_special_character = strchr(password, '!');
printf("%d\n", contains_special_character);
}

putting '0' before ID number that the user input [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm a new c programmer.
I was asked to get an ID number as an input and if the ID length < 9 I need to put '0' before the number.
example:
input: 12345
output: 000012345
I can use the libraries: stdio, stdlib, string, math and time.
You can use printf for this:
#include <stdio.h>
int main () {
printf("%09d\n", 12345);
return(0);
}
Documentation
There is an easy solution in here.
But if you want a hard solution, where you juggle around with strings and such, you can do the following:
convert your id into a string (if it isn't already one, but argv should a string by default)
calculate the number of zeros you need, by doing 9-idString Length
create a "buffer" string variable
for loop from 0 to 9-idString and use strcat to add "0"s to your buffer string.
add your id to your buffer string using strcat
Example code would be something like this:
int id = 12345;
char idstring[10];
char buffer[10];
sprintf(idstring, "%d", id);
int missingZerosCount = 9 - strlen(idstring);
strcpy(buffer, "");
while (missingZerosCount > 0) {
strcat(buffer, "0");
missingZerosCount--;
}
strcat(buffer, idstring);
argv variant:
char idstring[10];
char buffer[10];
sprintf(idstring, "%s", argv[1]);
int missingZerosCount = 9 - strlen(idstring);
strcpy(buffer, "");
while (missingZerosCount > 0) {
strcat(buffer, "0");
missingZerosCount--;
}
strcat(buffer, idstring);

Semantically identical codes give different results [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I couldn't wrap my head around this one, hope the title isn't too misleading. Why does write behave differently when it comes to it's third argument count in the two snippets of code? It would seem that calling a function instead of specifying a number in write is a bad thing, but it doesn't seem like a big deal.
Wrong version:
int main(int argc, char const *argv[])
{
char format[50];
char formattedTime[50];
time_t t;
if (read(STDIN_FILENO, format, 50) < 0)
fatalError("read() error");
time(&t);
strftime(formattedTime, 50, format, localtime(&t));
if (write(STDOUT_FILENO, formattedTime, strlen(formattedTime) + 1) != strlen(formattedTime) + 1)
fatalError("write() error");
return 0;
}
Right version:
int main(int argc, char const *argv[])
{
char format[50]; //zeljeni format
char formattedTime[50]; //formatirano vreme
time_t t; // trenutno vreme
// citamo s ulaza zeljeni format vremena
if (read(STDIN_FILENO, format, 50) < 0)
fatalError("read() error");
// zapisujemo trenutno vreme
time(&t);
strftime(formattedTime, 50, format, localtime(&t));
int n;
n = strlen(formattedTime) + 1;
// ispisujemo na izlaz
if (write(STDOUT_FILENO, formattedTime, n) != n)
fatalError("write() error");
return 0;
}
Right output:
%a %b %d
Wed Jan 16
Wrong output:
%a %b %d
Wed Jan 16
0
Why would calcuating n just a step before the call to write make all the difference?
EDIT:
Hope this satisfies all the info. The gibberish is different every time, but the point remains.
If you really have that behavior this probably means the null character is missing in formattedTime and by chance n is just after in the stack and introduces a null char by its presence, or an equivalent because of the data saved in the stack
The read function is primarily intended to read binary data, not strings. As such, it reads only the characters you enter (i.e. a sequence of characters followed by a newline) without adding a null terminating byte. As a result, you don't have a properly formatted string, so using strftime can read past what was written into bytes that were not initialized and possibly past the end of the array. This invokes undefined behavior.
The "right version" seems to work because you got "lucky". That's one of the ways undefined behavior can manifest itself. Other people could see the opposite results of what you see.
You need to capture how many bytes were read and manually add a terminating null byte to the array:
int rval;
if ((rval=read(STDIN_FILENO, format, 49)) < 0)
fatalError("read() error");
format[rval] = 0;

issue in file handling in c [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Hi i am trying to read two characters from a file and want to send it to uint8_t* as hexadecimal .
Code:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int file_handling();
int main()
{
uint8_t *output ;
output=file_handling() ;
printf("\noutput_main --> %02x",output);
}
int file_handling()
{
uint8_t *output_hand ;
char c;
FILE *f_gets = fopen("filename", "r");
if(f_gets==NULL)
{
printf("Please point to a valid key file!\n");
fclose(f_gets);
return 0;
}
char str[3];
if( fgets (str, 3, f_gets)!=NULL )
{
/* writing content to stdout */
puts(str);
output_hand = (uint8_t *)(str);
puts(output_hand);
printf("\noutput %s --- %02x --> size --> %lu",str,*output_hand,sizeof(*output_hand));
}
fclose(f_gets);
return *output_hand;
}
following is output
we we
output we --- 77 --> size --> 1 output_main --> 65
what i can understand is 77 is ascii for w and 65 is ascii for e
but i want to put "we" which i suppose is a hex in uint8_t *output
where is the problem
in main ,if i use pointer "*output=file_handling()" instead of just output i get segmentation fault.
How to read value from a file and put it into uint8_t , where file is having hex characters,how fget identifies it as hex or char.
Thanks
file is a text file
ab
fe
ea
ce
1d
Basically
uint8_t *output;
*output = 0xFA ;
it works
but i want to read from above file and put it into output variable
You have plenty of problems, here's three of them:
You define str to be an array of two characters, which means it can only contain a single-character string. You then call fgets telling it that str it three characters, which means it can and will write out of bounds of your array.
You have declared file_handling to return an int value. You return the first character in the array string, and assign that to the pointer variable output in the main function. You then treat this pointer as a single int value.
In the main function you pass the pointer output but print it as an int value. There's a mismatch between the format specifier and the argument.
The first and third issues lead to undefined behavior.

counting number of digits in a number which contains zeros at the left side [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
How can we count the number of digits in a number which contains zeros at the left side? For example for the integer input 0012, it should display 4 and for integer input 0000 it again should display 4. Actually, first I want to check the number of digits in the number and then want to check whether it is even or odd.
More examples to clear the understanding for number of digits:
integer input:012 output:3
integer input:00001 output:5
integer input:1010 output:4
Here is a simple way to compute the number of digits at the start of a string, including initial zeroes:
#include <string.h>
size_t count_digits(const char *s) {
return strspn(s, "0123456789");
}
strspn(), a lesser known but standard function, counts the number of characters at the start of its first string argument that are present in the second string argument. Its counterpart strcspn() counts the characters that are not present in the second string argument, it can be used to remove the trailing newline from the buffer filled by fgets(): buf[strcspn(buf, "\n")] = '\0';.
chqrlie's answer is arguably the simplest possible solution in C if you don't want to go with a simple strlen(). The following would be a bit more efficient:
#include <stdio.h>
#include <ctype.h>
size_t numDigits(const char *str)
{
size_t n = 0;
// increment counter while the character is a digit:
while (isdigit(str[n])) ++n;
return n;
}
int main(int argc, char **argv)
{
if (argc != 2)
{
fprintf(stderr, "Usage: %s [number]\n", argv[0]);
return 1;
}
size_t digits = numDigits(argv[1]);
if (argv[1][digits]) // not end of string after the digits found
{
puts("not a number");
}
else
{
printf("%zu digits\n", digits);
}
return 0;
}
I'm new here but most languages have a trim left & right function to remove spaces and a Len function to return a string length so something like:
nbrdigits = len(rtrim(ltrim(inputstring)))
Assuming that only digits were input.

Resources