I'm very new to C. I want to construct a string using 3 integers and "/".
Eg.
int a=01;
int b=10;
int c=2012;
char date = "a/b/c";
Can you please help and let me know what is the correct way to do this.
Thanks in advance
You should allocate enough buffer and use sprintf().
int a=01; /* this is octal value */
int b=10;
int c=2012;
char date[40]; /* 32-bit long integer will be at most 11 digits including sign in decimal */
sprintf(date, "%d/%d/%d", a, b, c);
Try this:
#include <stdio.h>
int main()
{
int a=1;
int b=10;
int c=2012;
char date[11];
sprintf(date, "%d/%d/%d", a, b, c);
printf("%s\n", date);
sprintf(date, "%02d/%02d/%04d", a, b, c);
printf("%s\n", date);
return 0;
}
This prints the date in two formats. The second zero-pads while the first does not. Here's the output:
1/10/2012
01/10/2012
Use sprintf, which will write to a string, as the name suggests: string print function:
sprintf(date, "%d/%d/%d", a, b, c);
and include the header stdio.h.
Also, doing
char date;
makes date a character, but you want it to be a string. So allocate memory in it:
char date [10];
which makes it a string or an array of characters with 10 elements. But you will be able to store only 9 characters in it, as you have to keep one element for the null-terminator or \0.
How does sprintf work?
If you're confused what sprintf is doing, basically the first argument is where sprintf is printing, the second argument is what to print, and the third, fourth, etc.. arguments are variables which will be substituted by a %d, %s, etc.
For a better explanation, see this:
The C library function sprintf () is used to store formatted data as a string. You can also say the sprintf () function is used to create strings as output using formatted data. The syntax of the sprintf () function is as follows:
int sprintf (char *string, const char *form, … );
You can also use itoa, but it is not standard.
Related
I was given a skeleton code to build an AddressBook program in C language. The code gives me a helper function get_option() to obtain user input that returns an integer. The driver code, however, requires me to return a character from using get_option(). Please help
get_option() function and the function that calls get_option()
Here are the global variables declared in a header file(not important)
global variable declared in header file
To use an integer value as char, you can just make a cast from int to char, like the example:
int main() {
//int cast to char
int a = 78; //'N' code in ascii table
printf("%c\n", (char)a); //will print "N"
//char cast to int
char c = 't';
printf("%d\n", (int)c); //will print 116, that is the 't'code in ascii table
}
by doing this, your int will be treated as a char. But, you must be careful, because not all integer values have the char representation. For more details, you can search the ascii table. That is a table that codify the characters into integers.
So, because of that, you can treat an integer(not all) as a char and a char as an integer.
The function readFile(filename) reads the contents of the file and stores it in heap using malloc, it returns char* datatype. I want to store the content in an array in main so that I can count the words. How do I do so? This is the code:
int main()
{
char *char1;
char1 = readFile("test1.txt");
printf("%s", char1[0]); //This does not print anything
CountWords(*char1, &Alpha, &SentChk, &punct, &Words, &totalSents, &onlyVowel_e);
/*function header of CountWords: void CountWords(char ch, int *Alpha, int *SentChk, int *punct,
int *Words, int *totalSents, int *onlyVowel_e);*/
printf("%d", Words);
printf("%d", totalSents);
return 0;
}
When you call "Countwords", your arguments cant be seen by the main as they arent defined there. Even if you use them in your other funtion - this is a different scope. Maybe you could return a char*[] holding these paramaters you want to return. Or better yet, define all of those arguments in main, have your first function pass them "by reference". This way you have the values put in a place where you can access them later for your "Counwords"
I am very new to C programming and having trouble compiling what should be a very simple function. The function, called printSummary, simply takes 3 integers as arguments, then prints some text along with those integers. For example, if hits=1, misses=2, and evictions=3, then printSummary(hits,misses,evictions) should print the following:
hits:1 misses:2 evictions:3
Here is the code I'm using. Thanks in advance for any advice.
#include<stdio.h>
void printSummary(int hits, int misses, int evictions)
{
printf('hits: %d\n');
printf('misses: %d\n');
printf('evictions: %d\n');
}
int main()
{
int hit_count = 1;
int miss_count = 2;
int eviction_count = 3;
printSummary(hit_count, miss_count, eviction_count);
return 0;
}
Compiling this code gives me several warnings, but no errors. When I run the code, I get a segmentation fault. Like I said, I am fairly new to C so there is most likely a simply solution that I am just missing. Thanks in advance for any advice.
Make the below changes .
printf("hits: %d\n",hits);
printf("misses: %d\n",misses);
printf("evictions: %d\n",evictions);
printf has a
int printf(const char *format, ...)
prototype. So in the first argument you can pass format specifiers and in the next provide the actual variables/values to be printed out
errors are:
void printSummary(int hits, int misses, int evictions)
{
/* Name: printf
Prototype: int printf (const char *template, ...)
Description:
The printf function prints the optional arguments under the
control of the template string template to the stream stdout.
It returns the number of characters printed,or a negative value if
there was an output error.*/
printf("hits: %d\n", hits); // don't use ' it is used only for char variable for example: char a = 'c';
printf("misses: %d\n", misses);
printf("evictions: %d\n", evictions);
}
Your printf function is not being called correctly. You have to include the integers needed to print:
printf("hits: %d\n", hits);
printf("misses: %d\n", misses);
printf("evictions: %d\n", evictions);
Read more about the printf function here.
I'm trying to printf an integer that was passed by command line but the console print a long random values.
I put this into RUN "C:\Users\pc\Documents\Visual Studio 2013\Projects\Lab3\Debug\Lab3.exe randomString 4"
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]){
printf("%s\n", argv[0]); // Working
printf("%s\n", (argv[1])); // working
printf("%d\n", (int)(argv[2])); // NOT Working
printf("%d\n", argc); // Working
system("pause");
return 0;
}
You can't just "cast" a char* pointer to an int and expect it to be magically converted. That is just printing the address of the first element of the array. You need to convert it to an int with a runtime function such as atoi(argv[2]) See function details here
The argv[2] variable is a string pointer (char* to be precise). So casting it to int will just give you the numerical value of this pointer (or part of it, depending on the size of the addresses on your system). And this is exactly your "random long number" that you are seeing. In order to convert the string to a number you can use functions like atoi.
I just started to look at C, coming from a java background. I'm having a difficult time wrapping my head around pointers. In theory I feel like I get it but as soon as I try to use them or follow a program that's using them I get lost pretty quickly. I was trying to follow a string concat exercise but it wasnt working so I stripped it down to some basic pointer practice. It complies with a warning conflicting types for strcat function and when I run it, crashes completly.
Thanks for any help
#include <stdio.h>
#include <stdlib.h>
/* strcat: concatenate t to end of s; s must be big enough */
void strcat(char *string, char *attach);
int main(){
char one[10]="test";
char two[10]="co";
char *s;
char *t;
s=one;
t=two;
strcat(s,t);
}
void strcat(char *s, char *t) {
printf("%s",*s);
}
Your printf() should look like this:
printf("%s",s);
The asterisk is unnecessary. The %s format argument means that the argument should be a char*, which is what s is. Prefixing s with * does an extra invalid indirection.
You get the warning about conflicting types because strchr is a standard library routine, which should have this signature:
char * strcat ( char * destination, const char * source );
Yours has a different return type. You should probably rename yours to mystrchr or something else to avoid the conflict with the standard library (you may get linker errors if you use the same name).
Change
printf("%s",*s);
to
printf("%s",s);
The reason for this is printf is expecting a replacement for %s to be a pointer. It will dereference it internally to get the value.
Since you declared s as a char pointer (char *s), the type of s in your function will be just that, a pointer to a char. So you can just pass that pointer directly into printf.
In C, when you dereference a pointer, you get the value pointed to by the pointer. In this case, you get the first character pointed to by s. The correct usage should be:
printf( "%s", s );
BTW, strcat is a standard function that returns a pointer to a character array. Why make your own?
Replacing *s with s won't append strings yet, here is fully working code :
Pay attention to function urstrcat
#include <stdio.h>
#include <stdlib.h>
/* urstrcat: concatenate t to end of s; s must be big enough */
void urstrcat(char *string, char *attach);
int main(){
char one[10]="test";
char two[10]="co";
char *s;
char *t;
s=one;
t=two;
urstrcat(s,t);
return 0;
}
void urstrcat(char *s, char *t) {
printf("%s%s",s,t);
}
pointers are variable which points to address of a variable.
#include "stdio.h"
void main(){
int a,*b;
a=10;
b=&a;
printf("%d",b);
}
in the follwing code you will see a int 'a' and a pointer 'b'.
here b is taken as pointer of an integer and declared by giving'' before it.'' declare that 'b' is an pointer.then you will see "b=&a".this means b is taking address of integer "a" which is keeping value 10 in that particular memory and printf is printing that value.