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);
Related
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 6 years ago.
Improve this question
I have a string that looks like "AGE:83". I want to take the integer "83" out of this string, and I know that I should use the "sscanf" function. However, there is no white space between this string. How can I do that?
Use this:
const char *str = "AGE:83";
int age;
sscanf(str, "%*[^0-9]%d", &age);
This format will skip any non digits and parse an integer after that.
Note that it will fail if there are no non digit characters before the number. To handle the case where the number can be at the start of the string, use first try a direct match:
if (sscanf(str, "%d", &age) != 1
&& sscanf(str, "%*[^0-9]%d", &age) != 1) {
// no number found;
return 1;
}
// age was correctly extracted from `str`
Negative numbers cannot be parsed this way, unless you know the prefix does not contain a '-' (using format "%*[^0-9-]%d")
You can also use a string function to skip the prefix and convert the rest for atoi() or strtol():
age = atoi(str + strcspn(str, "0123456789"));
As noted by Enzo Ferber, if the format of the string is fixed and is known to start with AGE:, you can just convert the remainder of the string with:
age = atoi(str + 4);
But this would invoke undefined behavior if the string is shorter than 4 characters as you would be potentially dereferencing invalid addresses.
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
}
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 7 years ago.
Improve this question
How to find a number from each line of a text file?
For exemple in file is written:
Apple 500 America
Motorola 400 China
How i can find in a text file the int number (price)and to established if it is bigger than 450?
Given the format of the text file remains the same for all lines, you may use a combination of strtok and atoi to extract the number in between. Example:
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "Apple 500 America";
char *pch;
pch = strtok (str," \t\n"); // ignore 1st string
pch = strtok (NULL, " \t\n"); // get 2nd string
int i = atoi( pch ); // parse 2nd string to int
printf( "i = %d\n", i );
return 0;
}
Output:
i = 500
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 8 years ago.
Improve this question
I'm having the issues of trying to separate 1s or 2d into int 1 and char 's' and then storing them as separate values. How would I go about doing this. I know I can't do it with strtok since there are no delimiters.
Use strtol. For example,
char *endptr;
val = strtol(input_str, &endptr, 10;
next_char = *endptr;
As discussed in the manpage, http://man7.org/linux/man-pages/man3/strtol.3.html, the second parameter is a pointer to a char pointer and after the conversion, the char pointer points to the following character.
You can access each char from the string by index. To convert char to int (not by ascii value, '1' to 1) you just do the following:
int a = c[0]-'0';
and for the char:
char b = c[1];
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 9 years ago.
Improve this question
I'm trying to print in a file a string with a fixed size. Something like this:
#define SIZE 30
main()
{
FILE *fp = fopen("myfile.txt","w+");
char s[10];
sprintf(s, "my text");
fprintf(fp, "%SIZEs", s);
fclose(fp);
}
but I keep getting errors.. help?
You should define your format string like the following:
fprintf(fp, "%*s", SIZE, s); // Right aligned string
fprintf(fp, "%-*s", SIZE, s); // Left aligned string
From the printf man page:
The precision
Instead of a decimal digit string one may write "*" to specify that the precision is given in the next argument