I wrote this function that's supposed to do StringPadRight("Hello", 10, "0") -> "Hello00000".
char *StringPadRight(char *string, int padded_len, char *pad) {
int len = (int) strlen(string);
if (len >= padded_len) {
return string;
}
int i;
for (i = 0; i < padded_len - len; i++) {
strcat(string, pad);
}
return string;
}
It works but has some weird side effects... some of the other variables get changed. How can I fix this?
It might be helpful to know that printf does padding for you, using %-10s as the format string will pad the input right in a field 10 characters long
printf("|%-10s|", "Hello");
will output
|Hello |
In this case the - symbol means "Left align", the 10 means "Ten characters in field" and the s means you are aligning a string.
Printf style formatting is available in many languages and has plenty of references on the web. Here is one of many pages explaining the formatting flags. As usual WikiPedia's printf page is of help too (mostly a history lesson of how widely printf has spread).
For 'C' there is alternative (more complex) use of [s]printf that does not require any malloc() or pre-formatting, when custom padding is desired.
The trick is to use '*' length specifiers (min and max) for %s, plus a string filled with your padding character to the maximum potential length.
int targetStrLen = 10; // Target output length
const char *myString="Monkey"; // String for output
const char *padding="#####################################################";
int padLen = targetStrLen - strlen(myString); // Calc Padding length
if(padLen < 0) padLen = 0; // Avoid negative length
printf("[%*.*s%s]", padLen, padLen, padding, myString); // LEFT Padding
printf("[%s%*.*s]", myString, padLen, padLen, padding); // RIGHT Padding
The "%*.*s" can be placed before OR after your "%s", depending desire for LEFT or RIGHT padding.
[####Monkey] <-- Left padded, "%*.*s%s"
[Monkey####] <-- Right padded, "%s%*.*s"
I found that the PHP printf (here) does support the ability to give a custom padding character, using the single quote (') followed by your custom padding character, within the %s format.
printf("[%'#10s]\n", $s); // use the custom padding character '#'
produces:
[####monkey]
#include <stdio.h>
#include <string.h>
int main(void) {
char buf[BUFSIZ] = { 0 };
char str[] = "Hello";
char fill = '#';
int width = 20; /* or whatever you need but less than BUFSIZ ;) */
printf("%s%s\n", (char*)memset(buf, fill, width - strlen(str)), str);
return 0;
}
Output:
$ gcc -Wall -ansi -pedantic padding.c
$ ./a.out
###############Hello
You must make sure that the input string has enough space to hold all the padding characters. Try this:
char hello[11] = "Hello";
StringPadRight(hello, 10, "0");
Note that I allocated 11 bytes for the hello string to account for the null terminator at the end.
The argument you passed "Hello" is on the constant data area. Unless you've allocated enough memory to char * string, it's overrunning to other variables.
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
strncpy(buffer, "Hello", sizeof(buffer));
StringPadRight(buffer, 10, "0");
Edit: Corrected from stack to constant data area.
Oh okay, makes sense. So I did this:
char foo[10] = "hello";
char padded[16];
strcpy(padded, foo);
printf("%s", StringPadRight(padded, 15, " "));
Thanks!
#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
int main() {
// your code goes here
int pi_length=11; //Total length
char *str1;
const char *padding="0000000000000000000000000000000000000000";
const char *myString="Monkey";
int padLen = pi_length - strlen(myString); //length of padding to apply
if(padLen < 0) padLen = 0;
str1= (char *)malloc(100*sizeof(char));
sprintf(str1,"%*.*s%s", padLen, padLen, padding, myString);
printf("%s --> %d \n",str1,strlen(str1));
return 0;
}
The function itself looks fine to me. The problem could be that you aren't allocating enough space for your string to pad that many characters onto it. You could avoid this problem in the future by passing a size_of_string argument to the function and make sure you don't pad the string when the length is about to be greater than the size.
One thing that's definitely wrong in the function which forms the original question in this thread, which I haven't seen anyone mention, is that it is concatenating extra characters onto the end of the string literal that has been passed in as a parameter. This will give unpredictable results. In the example call of the function, the string literal "Hello" will be hard-coded into the program, so presumably concatenating onto the end of it will dangerously write over code. If you want to return a string which is bigger than the original then you need to make sure you allocate it dynamically and then delete it in the calling code when you're done.
#include<stdio.h>
#include <string.h>
void padLeft(int length, char pad, char* inStr,char* outStr) {
int minLength = length * sizeof(char);
if (minLength < sizeof(outStr)) {
return;
}
int padLen = length - strlen(inStr);
padLen = padLen < 0 ? 0 : padLen;
memset(outStr, 0, sizeof(outStr));
memset(outStr, pad,padLen);
memcpy(outStr+padLen, inStr, minLength - padLen);
}
Related
I am currently learning C, and so I wanted to make a program that asks the user to input a string and to output the number of characters that were entered, the code compiles fine, when I enter just 1 character it does fine, but when I enter 2 or more characters, no matter what number of character I enter, it will always say there is just one character and crashes after that. This is my code and I can't figure out what is wrong.
int main(void)
{
int siz;
char i[] = "";
printf("Enter a string.\n");
scanf("%s", i);
siz = sizeof(i)/sizeof(char);
printf("%d", siz);
getch();
return 0;
}
I am currently learning to program, so if there is a way to do it using the same scanf() function I will appreciate that since I haven't learned how to use any other function and probably won't understand how it works.
Please, FORGET that scanf exists. The problem you are running into, whilst caused mostly by your understandable inexperience, will continue to BITE you even when you have experience - until you stop.
Here is why:
scanf will read the input, and put the result in the char buffer you provided. However, it will make no check to make sure there is enough space. If it needs more space than you provided, it will overwrite other memory locations - often with disastrous consequences.
A safer method uses fgets - this is a function that does broadly the same thing as scanf, but it will only read in as many characters as you created space for (or: as you say you created space for).
Other observation: sizeof can only evaluate the size known at compile time : the number of bytes taken by a primitive type (int, double, etc) or size of a fixed array (like int i[100];). It cannot be used to determine the size during the program (if the "size" is a thing that changes).
Your program would look like this:
#include <stdio.h>
#include <string.h>
#define BUFLEN 100 // your buffer length
int main(void) // <<< for correctness, include 'void'
{
int siz;
char i[BUFLEN]; // <<< now you have space for a 99 character string plus the '\0'
printf("Enter a string.\n");
fgets(i, BUFLEN, stdin); // read the input, copy the first BUFLEN characters to i
siz = sizeof(i)/sizeof(char); // it turns out that this will give you the answer BUFLEN
// probably not what you wanted. 'sizeof' gives size of array in
// this case, not size of string
// also not
siz = strlen(i) - 1; // strlen is a function that is declared in string.h
// it produces the string length
// subtract 1 if you don't want to count \n
printf("The string length is %d\n", siz); // don't just print the number, say what it is
// and end with a newline: \n
printf("hit <return> to exit program\n"); // tell user what to do next!
getc(stdin);
return 0;
}
I hope this helps.
update you asked the reasonable follow-up question: "how do I know the string was too long".
See this code snippet for inspiration:
#include <stdio.h>
#include <string.h>
#define N 50
int main(void) {
char a[N];
char *b;
printf("enter a string:\n");
b = fgets(a, N, stdin);
if(b == NULL) {
printf("an error occurred reading input!\n"); // can't think how this would happen...
return 0;
}
if (strlen(a) == N-1 && a[N-2] != '\n') { // used all space, didn't get to end of line
printf("string is too long!\n");
}
else {
printf("The string is %s which is %d characters long\n", a, strlen(a)-1); // all went according to plan
}
}
Remember that when you have space for N characters, the last character (at location N-1) must be a '\0' and since fgets includes the '\n' the largest string you can input is really N-2 characters long.
This line:
char i[] = "";
is equivalent to:
char i[1] = {'\0'};
The array i has only one element, the program crashes because of buffer overflow.
I suggest you using fgets() to replace scanf() like this:
#include <stdio.h>
#define MAX_LEN 1024
int main(void)
{
char line[MAX_LEN];
if (fgets(line, sizeof(line), stdin) != NULL)
printf("%zu\n", strlen(line) - 1);
return 0;
}
The length is decremented by 1 because fgets() would store the new line character at the end.
The problem is here:
char i[] = "";
You are essentially creating a char array with a size of 1 due to setting it equal to "";
Instead, use a buffer with a larger size:
char i[128]; /* You can also malloc space if you desire. */
scanf("%s", i);
See the link below to a similar question if you want to include spaces in your input string. There is also some good input there regarding scanf alternatives.
How do you allow spaces to be entered using scanf?
That's because char i[] = ""; is actually an one element array.
Strings in C are stored as the text which ends with \0 (char of value 0). You should use bigger buffer as others said, for example:
char i[100];
scanf("%s", i);
Then, when calculating length of this string you need to search for the \0 char.
int length = 0;
while (i[length] != '\0')
{
length++;
}
After running this code length contains length of the specified input.
You need to allocate space where it will put the input data. In your program, you can allocate space like:
char i[] = " ";
Which will be ok. But, using malloc is better. Check out the man pages.
I need to form a string, inside each iteration of the loop, which contains the loop index i:
for(i=0;i<100;i++) {
// Shown in java-like code which I need working in c!
String prefix = "pre_";
String suffix = "_suff";
// This is the string I need formed:
// e.g. "pre_3_suff"
String result = prefix + i + suffix;
}
I tried using various combinations of strcat and itoa with no luck.
Strings are hard work in C.
#include <stdio.h>
int main()
{
int i;
char buf[12];
for (i = 0; i < 100; i++) {
snprintf(buf, 12, "pre_%d_suff", i); // puts string into buffer
printf("%s\n", buf); // outputs so you can see it
}
}
The 12 is enough bytes to store the text "pre_", the text "_suff", a string of up to two characters ("99") and the NULL terminator that goes on the end of C string buffers.
This will tell you how to use snprintf, but I suggest a good C book!
Use sprintf (or snprintf if like me you can't count) with format string "pre_%d_suff".
For what it's worth, with itoa/strcat you could do:
char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");
Look at snprintf or, if GNU extensions are OK, asprintf (which will allocate memory for you).
I am processing an input string, which consists of a process name, followed by an arbitrary amount of arguments.
I need the process name , along with all of the arguments, in one string.
I thought I could use strcat in a loop, so that it cycles through all of the args and each time appends the arg to the string, but I am having problems with getting a string that in empty to begin the loop.
Can anyone help me out with some basic code?
Thanks.
EDIT:
I'm posting my code for clarity. Mike's post is closest to what I have now:
char * temp;
strcpy(temp,"");
for (i = 4; i < argc-1; i++) // last arg is null, so we need argc-1
{
strcat(temp,argv[i]);
strcat(temp," ");
}
ignore the 4 in my for loop for the moment (magic number, i know.)
I am getting a segfault with this code. Is it because of my string assignment? I assume that is the case and hence I asked the question of how i could combine the strings.
Let's say your input strings are in an array of char pointers, suggestively called argv, of length argc.
We first need to determine how much space is needed for the output:
int length = 0;
for (int i = 0; i < argc; ++i)
length += strlen(argv[i]);
Then we allocate it, adding an extra char for the '\0' terminator:
char *output = (char*)malloc(length + 1);
Finally, the concatenation:
char *dest = output;
for (int i = 0; i < argc; ++i) {
char *src = argv[i];
while (*src)
*dest++ = *src++;
}
*dest = '\0';
Note that I don't use strcat here. Reason is that this sets us up for a Schlemiel the Painter's algorithm: for each iteration, the entire output string would be scanned to find its end, resulting in quadratic running time.
Don't forget to free the output string when you're done:
free(output);
I'm a bit tired so I may be overlooking something here. A better solution, using standard library functions, is welcome. It would be convenient if strcat returned a pointer to the terminator byte in dest, but alas.
You want an empty C string? Is this what you are looking for: char p[] = "";?
UPDATE
After you posted some code it is clear that you have forgotten to allocate the buffer temp. Simply run around the arguments first, counting up the length required (using strlen), and then allocate temp. Don't forget space for the zero terminator!
You could provide the "arbitrary amount of arguments" as one argument, ie an array/list, then do this pseudocode:
str = "";
i = 0;
while i < length of input
{
str = strcat ( str , input[i]);
i++;
}
#include<stdio.h>
#include<stdarg.h>
int main(int argc, char** argv) {
// the main parameters are the same situation you described
// calling this program with main.exe asdf 123 fdsa, the program prints out: asdf123fdsa
int lengths[argc];
int sum =0;
int i;
for(i=1; i<argc; i++) { // starting with 1 because first arg is program-path
int len = strlen(argv[i]);
lengths[i] = len;
sum+=len;
}
char* all = malloc(sum+1);
char* writer = all;
for(i=1; i<argc; i++) {
memcpy(writer, argv[i], lengths[i]);
writer+=lengths[i];
}
*writer = '\0';
printf("%s\n", all);
system("pause");
return 0;
}
A string in C is represented by an array of characters that is terminated by an "null" character, '\0' which has the value 0. This lets all string functions know where the end of a string is. Here's an exploration of different ways to declare an empty string, and what they mean.
The usual way of getting an empty string would be
char* emptyString = "";
However, emptyString now points to a string literal, which cannot be modified. If you then want to concatenate to an empty string in your loop, you have to declare it as an array when you initialize.
char buffer[] = "";
This gives you an array of size one. I.e. buffer[0] is 0. But you want an array to concatenate to- it has to be large enough to accomodate the strings. So if you have a string buffer of certain size, you can initialize it to be empty like so:
char buffer[256] = "";
The string at buffer is now "an empty string". What it contains, is buffer[0] is 0 and the rest of the entries of the buffer might be garbage, but those will be filled once you concatenate your other strings.
Unfortunately, the problem with C, is you can never have an "infinite" string, where you are safe to keep concatenating to, you have to know it's definite size from the start. If your array of arguments are also strings, you can find their length using strlen. This gives you the length of a string, without the null character. Once you know the lengths of all your sub-strings, you will now know how long your final buffer will be.
int totalSize; // assume this holds the size of your final concatenated string
// Allocate enough memory for the string. the +1 is for the null terminator
char* buffer = malloc(sizeof(char) * (totalSize + 1));
buffer[0] = 0; // The string is now seen as empty.
After this, you are free to concatenate your strings using strcat.
#include<stdio.h>
main()
{
char str[50] = "Wel %s";
char dst[50];
snprintf(dst,50,str,"Come");
//Now i want to append "*" to dst string ie "Wel Come*" using snprintf()
printf("str = %s\n",str);
printf("dst = %s\n",dst);
}
please suggest is it possible using snprintf()
Thanks
Surya
The obvious solution:
snprintf(dst,50,"%s*",dst);
is inefficient, because it makes an unnecessary copy of dst (into itself).
invokes undefined behavior as R. pointed out, because the arguments may not overlap (from man snprintf(3) on MacOSX):
"[...]or those routines that write to
a user-provided character string, that
string and the format strings should
not overlap, as the behavior is
undefined."
Posix says:
http://www.opengroup.org/onlinepubs/000095399/functions/printf.html
"If copying takes place between
objects that overlap as a result of a
call to sprintf() or snprintf(), the
results are undefined."
snprintf returns the number of characters it has written, so you can do this instead:
int k=snprintf(dst,50,str,"Come");
// make sure that we do not pass potential disastrous values to snprintf, because
// the size argument is unsigned (size_t, 50-52 is a large positive number!)
// and we want 50-k to be in the range 0-50
// k<0 means output error and k>50 means "output truncated". There is no point in
// appending anything in these cases anyway.
if (k<0 || k>50)
{
fprintf(stderr,"output error or buffer too small");
}
else k=snprintf(dst+k,50-k,"*");
// check k for truncation here.
And then there's always strcat...And just in case, you overlooked it. You can have the * attached right in the first place:
main()
{
char str[50] = "Wel %s*"; //<--!!!
[...]
This should work:
#include<stdio.h>
int main()
{
char str[50] = "Wel %s";
char dst[50];
int len;
snprintf(dst,50,str,"Come");
//get size of current string
len = strlen(dst);
//add character to the end
snprintf(dst + len, sizeof(dst) - len, "*");
printf("str = %s\n",str);
printf("dst = %s\n",dst);
return 0;
}
you can use the %s format for this:
snprintf(dst, 50, "%s*", dst);
EDIT: This seems to have some undefined behaviors. The best thing would be to ask if it is really necessary to use snprintf instead of strncat.
All the information is already available to you:
snprintf(dst + 8, sizeof(dst) - 8, "%s", "*");
You'd be better off doing:
strncat(dst, "*", sizeof(dst) - strlen(dst) - 1);
Let's say I have a char* str = "0123456789" and I want to cut the first and the last three letters and print just the middle, what is the simplest, and safest, way of doing it?
Now the trick: The portion to cut and the portion to print are of variable size, so I could have a very long char*, or a very small one.
You can use printf(), and a special format string:
char *str = "0123456789";
printf("%.6s\n", str + 1);
The precision in the %s conversion specifier specifies the maximum number of characters to print. You can use a variable to specify the precision at runtime as well:
int length = 6;
char *str = "0123456789";
printf("%.*s\n", length, str + 1);
In this example, the * is used to indicate that the next argument (length) will contain the precision for the %s conversion, the corresponding argument must be an int.
Pointer arithmetic can be used to specify the starting position as I did above.
[EDIT]
One more point, if your string is shorter than your precision specifier, less characters will be printed, for example:
int length = 10;
char *str = "0123456789";
printf("%.*s\n", length, str + 5);
Will print "56789". If you always want to print a certain number of characters, specify both a minimum field width and a precision:
printf("%10.10s\n", str + 5);
or
printf("%*.*s\n", length, length, str + 5);
which will print:
" 56789"
You can use the minus sign to left-justify the output in the field:
printf("%-10.10s\n", str + 5);
Finally, the minimum field width and the precision can be different, i.e.
printf("%8.5s\n", str);
will print at most 5 characters right-justified in an 8 character field.
Robert Gamble and Steve separately have most of the pieces.
Assembled into a whole:
void print_substring(const char *str, int skip, int tail)
{
int len = strlen(str);
assert(skip >= 0);
assert(tail >= 0 && tail < len);
assert(len > skip + tail);
printf("%.*s", len - skip - tail, str + skip);
}
Invocation for the example:
print_substring("0123456789", 1, 3);
If you don't mind modifying the data, you could just do some pointer arithmetic. This is assuming that str is a char pointer and not an array:
char string[] = "0123456789";
char *str = string;
str += 3; // "removes" the first 3 items
str[4] = '\0'; // sets the 5th item to NULL, effectively truncating the string
printf(str); // prints "3456"
Here is a clean and simple substring function I dug up from my personal library that may be useful:
char *
substr(const char *src, size_t start, size_t len)
{
char *dest = malloc(len+1);
if (dest) {
memcpy(dest, src+start, len);
dest[len] = '\0';
}
return dest;
}
It's probably self-explanatory but it takes a string, a starting position (starting at zero), and a length and returns a substring of the original string or a null pointer if malloc fails. The pointer returned can be free'd by the caller when the memory is no longer needed. In the spirit of C, the function doesn't validate the starting position and length provided.
I believe there is some magic you can do with printf that will only print a certain number of characters, but it's not commonly understood or used. We tried to do it at a previous job and couldn't get it to work consistently.
What I would do is save off a character, null that character in the string, print it, then save it back.