I am trying to print each char in a variable.
I can print the ANSI char number by changing to this printf("Value: %d\n", d[i]); but am failing to actually print the string character itself.
What I am doing wrong here?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int len = strlen(argv[1]);
char *d = malloc (strlen(argv[1])+1);
strcpy(d,argv[1]);
int i;
for(i=0;i<len;i++){
printf("Value: %s\n", (char)d[i]);
}
return 0;
}
You should use %c format to print characters in C. You are using %s, which requires to use pointer to the string, but in your case you are providing integer instead of pointer.
The below will work. You pass in the pointer to a string when using the token %s in printf.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int len = strlen(argv[1]);
char *d = malloc (strlen(argv[1])+1);
strcpy(d,argv[1]);
printf("Value: %s\n", d);
return 0;
}
Related
I want to split a string by the comma and separate the first number in the string into its own new string, the rest of the string I want to keep together.
So far I have tried this by using strtok() and I can get the first number into its own string, but now I can't figure out how to keep the rest of the string together.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char testStr[] = "1000,first,second,third,+abc";
char *uidStr;
char *restOfstr;
int n;
//This is wrong, I know, but I want to populate
//the rest of the string after the first comma
//into a single string without the UID.
uidStr = strtok(testStr, ",");
while (n < 5)
{
restOfstr = strtok(NULL, ",");
n++;
}
return 0;
}
strtok works fine, you have to keep in mind that it returns a pointer to each tokenized word so you need two pointers one for the first token and other for the rest of the string.
Demo
#include <stdio.h>
#include <string.h>
int main()
{
char testStr[] = "1000,first,second,third,+abc";
char *uidStr; //pointer to uid
char *restOfstr; //pointers to the rest of the string
uidStr = strtok(testStr, ","); //uid remains in testStr
restOfstr = strtok(NULL, "\n"); //rest of the string
puts(uidStr); //or puts(testStr) to print uid
puts(restOfstr); //print rest of the string
return 0;
}
If you want a more secure function you can use strtok_s.
You can use strchr to find the first comma in the string.
Then using strncpy to get the number in the string.
The complete code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char *str = "1000,first,second,third,+abc";
char *s = strchr(str, ',');
if(!s)
return -1;
char num[10];
strncpy(num, str, s-str);
num[s-str] = '\0';
int a = strtol(num, NULL, 10);
printf("num = %d\nthe remaining: %s\n", a, s+1);
return 0;
}
#include <string.h>
#include <stdio.h>
int main(int ac, char **av) {
while (--ac) {
char *p = *++av;
char *t = strtok(p, ",");
char *r = strtok(NULL,"");
printf("%s : %s\n", t, r);
}
return 0;
}
Note that the empty string "" passed to the second strtok means that it cannot find a deliminator, thus returns the rest of the string.
In addition to the excellent answers #mevets and #anastaciu have provided (I would go with these), this code will also work fine.
#include <string.h>
#include <stdio.h>
int main(int argc, char** argv) {
char _p[] = "1000,Hey,There";
char* str1 = strtok(_p, ",");
char* str2 = strtok(NULL, "");
return 0;
}
i am trying to insert a comma in a large integer number eg, 870120000 and present it as: 870,120 and the last three digits are discarded. The format will allways be the same, ie., xxxxxxxxx number where i am only interested in the first 6 digits.
What i have been doing so fare is using snprintf:
#include <stdio.h>
#include <string.h>
int main()
{
char buffer[5];
unsigned int lNum= 870120000;
int cx;
memset(buffer,0,sizeof(buffer));
cx = snprintf(buffer, 4, "%d,", lNum);
buffer[3] = ',';
printf("%s\n",buffer);
cx = snprintf(buffer+4, 4, "321"); // Note 1 ???
printf("%s\n", buffer);
return 0;
}
My problem is that i am stuck at (comment // Note 1), how do I add the last next three digits in to buffer ?
in addition I would like to know if this approch is ideal or is there any better(easier) way to do this?
You can do that in two steps. First convert the lNum into a string, then cut the needed parts out of this string. Something like that.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char tmp[256], out[256];
unsigned int lNum= 870120000;
sprintf(tmp, "%u", lNum);
sprintf(out, "%3.3s,%3.3s", tmp, tmp+3);
printf("%s\n", out); // prints 870,120
return 0;
}
See http://ideone.com/bnQNou
Or you can convert it into a float and change the locale to have "," as delimiter:
#include <stdio.h>
#include <locale.h>
int main()
{
unsigned int lNum = 870120000;
setlocale(LC_NUMERIC, "de_DE");
printf("%3.3f\n", (float)(870120000 / 1000000)); // prints 870,120
return 0;
}
First of all to hold 870,120 you have to define a 8 chars buffer.
So you can use %f format specifier to do what you the job, e.g.:
#include <stdio.h>
#include <string.h>
int main()
{
char buffer[8] = {0};
unsigned int lNum= 870120000;
snprintf(buffer, sizeof(buffer), "%3.3f", (float)(lNum)/(1000000));
char *temp = strstr(buffer, ".");
if (temp != NULL)
{
*temp = ',';
}
printf("%s\n",buffer);
return 0;
}
or another example using double snprintf and a given number of integer part digits and decimal part digits.
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#define INT_DIGIT 3
#define DEC_DIGIT 3
int main()
{
char temp_buffer[128];
char buffer[INT_DIGIT+DEC_DIGIT+2] = {0};
unsigned int lNum= 87012000;
snprintf(temp_buffer, sizeof(temp_buffer), "%u",lNum);
snprintf(buffer, sizeof(buffer), "%.*s,%.*s", INT_DIGIT, temp_buffer, DEC_DIGIT, &temp_buffer[INT_DIGIT]);
printf("%s\n",buffer);
return 0;
}
Here's my code:
#include <stdio.h>
#include <string.h>
char input_buffer[1000];
void get_substring(){
int i;
int length;
printf("Please enter a string:\n");
scanf("%[^\n]s", input_buffer);
printf("Index of first character of substring:\n");
scanf("%d", &i);
printf("Length of substring:\n");
scanf("%d", &length);
printf("Substring is %.*s ", length, input_buffer + i);
}
int main(void) {
// your code goes here
//get_substring(0,4);
get_substring();
return 0;
}
That's my current code, I want to return a pointer of the input, instead of just displaying the substring. Sorry for the confusion everyone.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* getSubstring(char* str,size_t start, size_t length)
{
// determine that we are not out of bounds
if(start + length > strlen(str))
return NULL;
// reserve enough space for the substring
char *subString = malloc(sizeof(char) * length);
// copy data from source string to the destination by incremting the
// position as much as start is giving us
strncpy(subString, str + start, length);
// return the string
return subString;
}
int main(int argc, char* argv[])
{
char *str = "Hallo Welt!";
char *subStr = getSubstring(str,0,20);
if(subStr != NULL)
{
printf("%s\n",subStr);
free(subStr);
}
}
This solution should give you a hint how you would start with such a problem.
I'm new to C and trying to create a function that check a string and returns the last character.
I get the function to print the correct letter, but I cant figure out how to return it :/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char last_chr(char *c);
int main (int argc, const char * argv[]) {
char *text[15];
strcpy(text, "*find:last;char#");
last_chr(text); //debugging
//printf("last char: %c", last_chr(text)); //not working
return 0;
}
char last_chr(char *c) {
char *endchr;
char result;
int pos = strlen(c)-1;
endchr = c[pos];
//sprintf(result,"%s",endchr); //"EXEC_BAD_ACCESS"
putchar(endchr); //prints #
//putc(endchr, result); //"EXEC_BAD_ACCESS"
//printf(endchr); //"EXEC_BAD_ACCESS"
return result;
}
You don't assign result. You probably mean
result = c[pos];
instead of endchr = c[pos];
endchr is a character-pointer instead of a character.
#include <stdio.h>
#include <string.h>
char last_chr(char *c);
int main (int argc, const char * argv[]) {
char text[32];//char *text[15]
strcpy(text, "*find:last;char#");//length is 17
printf("last char: %c", last_chr(text));//#
return 0;
}
char last_chr(char *c) {
if(c == NULL || *c == '\0') return 0;
return c[strlen(c)-1];
}
snprintf in a loop does not work on linux but it works properly on windows.
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char **argv) {
char buffer[255] ={0};
for ( int i = 0; i < 10; i++) {
snprintf(buffer, 255, "%s:%x\0",buffer, i );
}
printf ( "BUFFER = %s\n", buffer );
return 0;
}
This code does not append existing buffer but only takes the last iteration value.
You can avoid the undefined behavior of using the buffer both as the target string and as an argument like this:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char **argv) {
char buffer[255] ={0};
int offset = 0;
for ( int i = 0; i < 10; i++) {
offset += snprintf(buffer + offset, 255 - offset, ":%x\0", i);
}
printf ( "BUFFER = %s\n", buffer );
return 0;
}
sprintf()'ing the result array to itself is undefined behaviour.
EDIT: if you want some code that works, here you are: use strcat() (or the safer strncat, etc. insert usual security discussion about buffer overflow here):
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char **argv) {
char buffer[255] = { 0 };
char fmtbuf[64];
int i;
for (i = 0; i < 10; i++) {
snprintf(fmtbuf, 64, "%x", fmtbuf, i);
strcat(buffer, fmtbuf);
}
printf ("BUFFER = %s\n", buffer);
return 0;
}
Also note that printf() calls don't need the terminating zero to be written out manually -- it's automatically added.
snprintf does work as specified on Linux, but your code does not append it. Read the Note in the linked documentation!
You should not use as its arguments (after the format string) the destination.
If you want it to append, either ensure that you don't overflow your fixed buffer, or reallocate that buffer when it gets too small.
You could not write 'buffer' to itself by 'snprintf'.
The test code is as follow:
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
int main( int argc, char **argv) {
char buffer[255] ={0};
for ( int i = 0; i < 10; i++) {
char tmp[255] = {0};
strcpy(tmp, buffer);
snprintf(buffer, 255, "%s:%x\0",tmp, i );
printf ( "BUFFER = %s\n", buffer );
}
printf ( "BUFFER = %s\n", buffer );
return 0;
}
The standard specifically states that this code is not expected to work. Firstly, the initial buffer argument is declared restrict, which means that it cannot alias another argument. Secondly, the standard has the following clause just for emphasis:
c99
7.19.6.5 The snprintf function
Description
2 - [...] If copying takes place between objects that overlap, the behavior is undeļ¬ned.