How do I convert a character to a string in C. I'm currently using c = fgetc(fp) which returns a character. But I need a string to be used in strcpy
To answer the question without reading too much else into it I would
char str[2] = "\0"; /* gives {\0, \0} */
str[0] = fgetc(fp);
You could use the second line in a loop with whatever other string operations you want to keep using chars as strings.
You could do many of the given answers, but if you just want to do it to be able to use it with strcpy, then you could do the following:
...
strcpy( ... , (char[2]) { (char) c, '\0' } );
...
The (char[2]) { (char) c, '\0' } part will temporarily generate null-terminated string out of a character c.
This way you could avoid creating new variables for something that you already have in your hands, provided that you'll only need that single-character string just once.
Using fgetc(fp) only to be able to call strcpy(buffer,c); doesn't seem right.
You could simply build this buffer on your own:
char buffer[MAX_SIZE_OF_MY_BUFFER];
int i = 0;
char ch;
while (i < MAX_SIZE_OF_MY_BUFFER - 1 && (ch = fgetc(fp)) != EOF) {
buffer[i++] = ch;
}
buffer[i] = '\0'; // terminating character
Note that this relies on the fact that you will read less than MAX_SIZE_OF_MY_BUFFER characters
I use this to convert char to string (an example) :
char c = 'A';
char str1[2] = {c , '\0'};
char str2[5] = "";
strcpy(str2,str1);
A code like that should work:
int i = 0;
char string[256], c;
while(i < 256 - 1 && (c = fgetc(fp) != EOF)) //Keep space for the final \0
{
string[i++] = c;
}
string[i] = '\0';
//example
char character;//to be scanned
char merge[2];// this is just temporary array to merge with
merge[0] = character;
merge[1] = '\0';
//now you have changed it into a string
This is an old question, but I'd say none of the answers really fits the OP's question. All he wanted/needed to do is this:
char c = std::fgetc(fp);
std::strcpy(buffer, &c);
The relevant aspect here is the fact, that the second argument of strcpy() doesn't need to be a char array / c-string. In fact, none of the arguments is a char or char array at all. They are both char pointers:
strcpy(char* dest, const char* src);
dest : A non-const char pointer
Its value has to be the memory address of an element of a writable char array (with at least one more element after that).
src : A const char pointerIts value can be the address of a single char, or of an element in a char array. That array must contain the special character \0 within its remaining elements (starting with src), to mark the end of the c-string that should be copied.
Here is a working exemple :
printf("-%s-", (char[2]){'A', 0});
This will display -A-
FYI you dont have string datatype in C. Use array of characters to store the value and manipulate it. Change your variable c into an array of characters and use it inside a loop to get values.
char c[10];
int i=0;
while(i!=10)
{
c[i]=fgetc(fp);
i++;
}
The other way to do is to use pointers and allocate memory dynamically and assign values.
Related
From my book:
void strcpy (char *s, char *t)
{
int i=0;
while ((s[i] = t[i]) != ’\0’)
++i;
}
I'm trying to understand this snippet of code from my textbook. They give no main function so I'm trying to wrap my head around how the parameters would be used in a call to the function. As I understand it, the "i-number" of characters of string t[ ] are being copied to the string s[ ] until there are no longer characters to read, from the \0 escape sequence. I don't really understand how the parameters would be defined outside of the function. Any help is greatly appreciated. Thank you.
Two things to remember here:
Strings in C are arrays of chars
Arrays are passed to functions as pointers
So you would call this like so:
char destination[16];
char source[] = "Hello world!";
strcpy(destination, source);
printf("%s", destination);
i is just an internal variable, it has no meaning outside the strcpy function (it's not a parameter or anything). This function copies the entire string t to s, and stops when it sees a \0 character (which marks the end of a string by C convention).
EDIT: Also, strcpy is a standard library function, so weird things might happen if you try to redefine it. Give your copy a new name and all will be well.
Here's a main for you:
int main()
{
char buf[30];
strcpy(buf, "Hi!");
puts(buf);
strcpy(buf, "Hello there.");
puts(buf);
}
The point of s and t are to accept character arrays that exist elsewhere in the program. They are defined elsewhere, at this level usually by the immediate caller or one more caller above. Their meanings are replaced at runtime.
Your get compile problems because your book is wrong. Should read
const strcpy (char *s, const char *t)
{
...
return s;
}
Where const means will not modify. Because strcpy is a standard function you really do need it to be correct.
Here is how you might use the function (note you should change the function name as it will conflict with the standard library)
void my_strcpy (char *s, char *t)
{
int i=0;
while ((s[i] = t[i]) != ’\0’)
++i;
}
int main()
{
char *dataToCopy = "This is the data to copy";
char buffer[81]; // This buffer should be at least big enough to hold the data from the
// source string (dataToCopy) plus 1 for the null terminator
// call your strcpy function
my_strcpy(buffer, dataToCopy);
printf("%s", buffer);
}
In the code, the i variable is pointing to the character in the character array. So when i is 0 you are pointing to the first character of s and t. s[i] = t[i]copies the i'th character from t to the i'th character of s. This assignment in C is self an expression and returns the character that was copied, which allows you to compare that to the null terminator 0 ie. (s[i] = t[i]) != ’\0’ which indicates the end of the string, if the copied character is not a null terminator the loop continues otherwise it will end.
I understand that in C, a string is an array of characters with a special '\0' character at the end of the array.
Say I have "Hello" stored in a char* named string and there is a '\0' at the end of the array.
When I call printf("%s\n", string);, it would print out "Hello".
My question is, what happens to '\0' when you call printf on a string?
The null character ('\0') at the end of a string is simply a sentinel value for C library functions to know where to stop processing a string pointer.
This is necessary for two reasons:
Arrays decay to pointers to their first element when passed to functions
It's entirely possible to have a string in an array of chars that doesn't use up the entire array.
For example, strlen, which determines the length of the string, might be implemented as:
size_t strlen(char *s)
{
size_t len = 0;
while(*s++ != '\0') len++;
return len;
}
If you tried to emulate this behavior inline with a statically allocated array instead of a pointer, you still need the null terminator to know the string length:
char str[100];
size_t len = 0;
strcpy(str, "Hello World");
for(; len < 100; len++)
if(str[len]=='\0') break;
// len now contains the string length
Note that explicitly comparing for inequality with '\0' is redundant; I just included it for ease of understanding.
I discovered mistake in my code (C). I declared zero length array,and it works.Problem is I don't know is that dangerous? I tried change it to
char c[1];
c[0] = '\0'; //or char c[1] = {""};
but then it does not work. There is my code:
void TranslateFile(struct keyElem* guard,FILE* inpFile,FILE* outFile)//"tłumaczy" plik spowrotem
{
char x;
char c[0] = {""};
char tab[100] = {""};
char empty[100] = {""};
while((feof(inpFile)==0))
{
fscanf(inpFile,"%c",&x);
if(x==' ')
{
c[0] = SearchChar(guard,tab);//get char from list
fprintf(outFile,"%s",c);
strcpy(tab,empty);
x = '\0'; //puts(tab);
}
if(x != ' ')
{
c[0] = x;
strcat(tab,c);
}
}
}
I dont know is it save or not and i dont know how to change it.
Zero length array should not be allowed. Which compiler do you user?
Use %c instead of %s in fprintf. %s needs a zero terminated char*, but your code has a char[1]. it might work in debug build when C[1] is '/0'. But in release version, the program may write a very long string into the output file until there is a '/0' in memory. If you must use a char array, declare a char[2] and set c[1] = '\0' in all cases.
"if (x != ' ')" logic is a bit strange. You have x = '\0' in the first if.
The standard doesn't allow it:
If the expression is a constant expression, it shall have a value
greater than zero. Array Declarations - From the standrad
However, GCC Allows it:
Non-empty initialization of zero-length arrays is treated like any
case where there are more initializer elements than the array holds,
in that a suitable warning about “excess elements in array” is given,
and the excess elements (all of them, in this case) are ignored. GCC - Arrays of Length Zero
So at best, all initialization values are ignored and you can't use that array in any practical way.
Ok I fixed it like user #wyc said.I wrote
void TranslateFile(struct keyElem* guard,FILE* inpFile,FILE* outFile)//"tłumaczy" plik spowrotem
{
char x;
char c[2] = {'\0','\0'};
char tab[100] = {""};
char empty[100] = {""};
while((feof(inpFile)==0))
{
fscanf(inpFile,"%c",&x);
if(x==' ')
{
c[0] = SearchChar(guard,tab);
fprintf(outFile,"%c",c[0]);
strcpy(tab,empty);
x = '\0';
printf("[%s]\n",c);
}
if(x != ' ')
{
c[0] = x;
strcat(tab,c);
}
}
}
and it works exactly.Thanks all of you for helpfull answers.Im begginer so i havent intuition for it yet;)
I have an array of characters declared as:
char *array[size];
When I perform a
printf("%s", array);
it gives me some garbage characters, why it is so?
http://www.cplusplus.com/reference/clibrary/cstdio/printf/
This url indicates printf takes in the format of: `int printf ( const char * format, ... );
#include <stdio.h>
#include <string.h>
#define size 20
#define buff 100
char line[buff];
int main ()
{
char *array[100];
char *sep = " \t\n";
fgets(line, buff, stdin);
int i;
array[0] = strtok(line, sep);
for (i = 1; i < size; i++) {
array[i] = strtok(NULL, sep);
if (array[i] == NULL)
break;
}
return 0;
}
You declare an array of characters like so:
char foo[size];
You seem to have it mixed up with char *, which is a pointer to a character. You could say
char *bar = foo;
which would make bar point to the contents of foo. (Or, actually, to the first character of foo.)
To then print the contents of the array, you can do one of the following:
// either print directly from foo:
printf("%s", foo);
// or print through bar:
printf("%s", bar);
Note, however, that C performs no initialization of the contents of variables, so unless you specifically set the contents to something, you'll get garbage. In addition, if that garbage doesn't happen to contain a \0; that is, a char with value 0, it will keep on outputting past the end of the array.
Your array is not initialized, and also you have an array of pointers, instead of an array of char's. It should be char* array = (char*)malloc(sizeof(char)*size);, if you want an array of char's. Now you have a pointer to the first element of the array.
Why are we making such a simple thing sound so difficult?
char array[SIZE];
... /* initialize array */
puts(array); /* prints the string/char array and a new line */
/* OR */
printf("%s", array); /* prints the string as is, without a new line */
The char in array after the end of what you want to be your string (ie. if you want your string to read "Hello" that would be the next char after the 'o') must be the terminating NUL character '\0'. If you use a C function to read input that would automatically be appended to the end of your buffer. You would only need to worry about doing it manually if you were individually writing characters to your buffer or something for some reason.
EDIT: As with pmg's comment, the '\0' goes wherever you want the string to end, so if you wanted to shorten your string you could just move it up closer to the front, or to have an empty string you just have array[0] = '\0';. Doing so can also be used to tokenise smaller strings inside a single buffer, just as strtok does. ie. "Part1\0Part2\0Part3\0". But I think this is getting away from the scope of the question.
ie. you wanted to store the first 3 chars of the alphabet as a string (don't know why anyone would do it this way but it's just an example):
char array[4];
array[0] = 'a';
array[1] = 'b';
array[2] = 'c';
array[3] = '\0';
printf("%s\n", array);
If you have something like char array[] = "Hello"; the '\0' is automatically added for you.
char *array[size];
array is not a char * with that, it's more like a char ** (pointer to an array of chars, with is similar to pointer to pointer to char).
If all you need is a C string, either:
char array[size];
and make sure you 0-terminate it properly, or
char *array;
and make sure you properly allocate and free storage for it (and 0-terminate it too).
Using GDB, I find I get a segmentation fault when I attempt this operation:
strcat(string,¤tChar);
Given that string is initialized as
char * string = "";
and currentChar is
char currentChar = 'B';
Why does this result in a segmentation fault?
If strcat can't be used for this, how else can I concat a char onto a string?
As responded by others, ¤tChar is a pointer to char or char*, but a string in C is char[] or const char*.
One way to use strcat to concatenate a char to string is creating a minimum string and use it to transform a char into string.
Example:
Making a simple string, with only 1 character and the suffix '\0';
char cToStr[2];
cToStr[1] = '\0';
Applying to your question:
char * string = "";
char currentChar = 'B';
cToStr will assume the string "B":
cToStr[0] = currentChar;
And strcat will work!
strcat ( string, cToStr );
Because ¤tChar is not a string, it doesn't finish with \0 character. You should define B as char *currentChar = 'B';. Also according to http://www.cplusplus.com/reference/clibrary/cstring/strcat string should have enough space to hold the result string (2 bytes in this case), but it is only 1 byte.
Or if you want to use char then you can do something like (depending of your code):
char string[256];
...
char currentChar = 'B';
size_t cur_len = strlen(string);
if(cur_len < 254) {
string[cur_len] = currentChar;
string[cur_len+1] = '\0';
}
else
printf("Not enough space");
I think the simplest method (not efficient) would be sprintf
sprintf(str, "%s%c", str, chr);
strcat() takes two '\0'-terminated strings. When you pass the address of a character, the routine will look at the memory that follows the character, looking for the terminator.
Since you don't know what that memory even refers to, you should expect problems when your code accesses it.
In addition to that, your string argument does not have room to have any characters appended to it. Where is that memory written to? It will attempt to write past the end of the memory associated with this string.
Both of the strings must be null-terminated. A single char isn't null terminated, so it's undefined when strcat will stop concatenating characters to the end. Also, string must contain at least enough space for both the original string and resultant string.
This works:
char string[10] = "";
char* currentChar = "B";
strcat(string, currentChar);
We know that currentChar = 'B'.
This can be done
strcat(string, "B\0");
If we know currentChar will be hardcoded as 'B', this would be a good approach.
It also removes the need for char currentChar = 'B';
The first argument of strcat must have enough space to hold the rest of the string. "" is a constant string and as such GCC does not allocate space.
Make it an array with enough space:
char buf[1024];
strcat(buf, "");
strcat(buf, "B");