convert int and char into a string - c

I have int x and char c. I want to make a new string called str as "x c"; so the int, a space, and the char.
So for example:
x = 5, c = 'k'
//concatenate int and char with a space in between.
so the line printf("%s", str) will print:
5 k
How do I do this in C code?

Use sprintf or snprintf to avoid safety of your code to be built on assumption that your buffer will be always big enough:
char str[100];
sprintf(str, 100, "%d %c", x, c);
But in case the only purpose of str will be to be used it to with printf, then just printf directly:
printf("%d %c", x, c);
...just don't use itoa since "this function is not defined in ANSI-C and is not part of C++"
These questions might help you as well:
How to convert an int to string in C
Converting int to string in c

char tmp[32]={0x0};
sprintf(tmp, "%d %c", x, c);
printf("%s\n", tmp);
or
printf("%d %c\n", x, c);

sprintf() can do what you want:
sprintf(str, "%d %c", x, c);

Since you want to print the information out, there is no reason (that I can see) to convert the data into a string first. Just print it out:
printf("%d %c", x, c);

Related

Why am i not getting the correct output

I am writing a piece of code to ask for two specific points in the format P0 x y.
If the user types in Q then the program terminates, for some reason I have trouble outputting the user input (P0 x y) into an output. When I try to run the code and type P0 2 3 it says I have chosen points 0 2.00 3.00.
While the desired output is P0 2 3.
#include <stdio.h>
void main() {
float a, b;
char Q, P, input;
printf("");
scanf("%c", &input);
if (input == 'Q') {
printf("quitting program");
return (0);
} else {
scanf("%c" "%f" "%f", &input, &a, &b);
printf("you have chose points: %c %f %f", input, a, b);
}
return (0);
}
Because you use two scanf. First scanf reads P then second scanf read 0 from command line (from stdin). So after second scanf, input = '0'. This is reason why your program prints 0 2.00 3.00
If you want to print out P0 you have to use string, for example the example below:
#include <stdio.h>
int main()
{
float a, b;
char Q, P, input;
char point[3] = {'\0'};
scanf( "%c" , &input);
point[0] = input;
if(input=='Q')
{
printf("quitting program");
return 0;
}
else
{
scanf( "%c" "%f" "%f", &input, &a, &b);
point[1] = input;
printf("you have chose points: %s %f %f",point, a, b);
}
return 0;
}
As the other answer also mentions, when checking for Q in input, the input byte is consumed. The C standard library provides a fix for this specific problem: you can "return" the consumed byte to the input device (keyboard buffer), and later retry reading from input.
The function is ungetc. It requires quite specific syntax (you should "unget" the same value as was just read; also you must use stdin to specify that you are working with keyboard) and only works for one byte, exactly as you need.
Here is your code with my updates and comments.
#include <stdio.h>
int main()
{
float a, b;
char Q; // only used for checking the "quit" condition
char input[10]; // assuming 9 characters + terminating byte is enough
scanf("%c", &Q);
if(Q=='Q')
{
printf("quitting program");
return (0);
}
else
{
ungetc(Q, stdin); // return one byte to the input device
scanf( "%s" "%f" "%f", input, &a, &b); // "%s" read from the input as string now
printf("you have chose points: %s %f %f",input, a, b);
}
return 0;
}

getting wrong output when using char and int [duplicate]

This question already has answers here:
Scanning with %c or %s
(2 answers)
Why does C's printf format string have both %c and %s?
(11 answers)
Closed 4 years ago.
Writing a simple code that's suppose to scan an integer and a character and then write them out.
my input is 1a and the output should be 1a but i'm getting 0 on the integer spot. have a pretty basic understanding of c so may have missed something that's pretty obvious thanks in advance.
#include <stdio.h>
int main()
{
int a;
char b;
scanf("%d", &a);
scanf(" %s", &b);
printf("%d", a);
printf("%s", &b);
}
b is a character so replace %s with %c, moreover
scanf() takes & before the variable as it want to store the variable refering to that address.
2.printf() Just outputs the value to the console present in that varaible.
Thereby no need to use & inside it
CORRECTED CODE:
#include <stdio.h>
int main()
{
int a;
char b;
scanf("%d", &a);
scanf(" %c", &b);
printf("%d", a);
printf("%c", b);
}
b is a char, %s is for string input so adds trailing 0 after b and you can get a crash. Use %c to input char.
You basically want this:
#include <stdio.h>
int main()
{
int a;
char b[100]; // array of 100 chars
scanf("%d", &a);
scanf("%s", b);
printf("%d", a);
printf("%s", b);
}
To fully understand this, you need to read the chapters dealing with scanf and the one dealing with strings in your C text book.
you can try it:
#include <stdio.h>
int main()
{
int a;
char b;
scanf("%d", &a);
scanf(" %c", &b);
printf("%d", a);
printf("%c", b);
}

sscanf() double & string

I am fairly new to the world of programming so please forgive me if this is a common mistake.
I'm trying to scan 3 double values and 3 strings out of one input string but it doesnt continue after the second value.
double total_weight_kg(char *s, int Length) {
double weights[3];
char units[3];
int test = sscanf(s, "%lf, %s, %lf, %s, %lf, %s",
&weights[0], &units[0],
&weights[1], &units[1],
&weights[2], &units[2]);
printf("%i\n", test);
printf("%s\n", &units[0]);
int main(void) {
total_weight_kg("5, g, 1, t, 175, kg", 3);
return 0;
The first print prints out 2 and the second the g.
Furthermore I'd like to compare units[i] in a loop but can't seem to get that working either.
for (int i = 0; i < Length; i++) {
w = weights[i];
if (strcmp(units[i], "kg") == 0) {
weight += w;
}
}
I hope you can help me find a solution for this problem,
edit: Everyting is working as intended now. Thank you very much for your help. ( 19[^,] was one major problem )
There are some problems in your code:
To scan the strings into units, you must define it as a 2D array of char:
char units[3][20];
You should modify the scanf format to stop the word parsing on , and spaces, as suggested by user3386109.
Also modify the printf to pass the array instead of its address.
Here is the modified code:
double total_weight_kg(char *s, int Length) {
double weights[3];
char units[3][20];
int test = sscanf(s, "%lf, %19[^, \n], %lf, %19[^, \n], %lf, %19[^, \n]",
&weights[0], units[0],
&weights[1], units[1],
&weights[2], units[2]);
printf("%i\n", test);
printf("%s\n", units[0]);
...
}
int main(void) {
total_weight_kg("5, g, 1, t, 175, kg", 3);
return 0;
}

How to understand the data move from A to B in character array?

#include <stdio.h>
int main ()
{
char a[10], b[9], c[5];
scanf("%s", a);
scanf("%s", b);
scanf("%s", c);
printf("%s\n", b);
printf("%s %s %s", a, b, c);
return 0;
}
when input c[] array's number > 5, the rest osf the characters will be wrriten to b[] array, why?
for example:
input:
program
is
wonderful
output:
rful
program rful wonderful
You're suffering C buffer overflow.
Try to avoid using scanf("%s", char[]) for this purpose.
Better use fgets() or similar.
Offtopic:
Interestingly this is related on how Nintendo's Wii was cracked. Or so it says the urban legend.

Converting a string of numbers into integers

I have a string (char) and I want to extract numbers out of it.
So I have string: 1 2 3 4 /0
And now I want some variables, so I can use them as integer: a=1, a=2, a=3, a=4
How can I do that?
The answers given so far are correct, as long as your string is formatted the way you expect. You should always check the return value of sscanf to make sure things worked okay. sscanf returns the number of conversions successfully performed, in the above case 4.
if (4 != sscanf(buf, "%d %d %d %d", &a, &b, &c, &d))
{
/* deal with error */
}
If buf was "1 2 3" or "1 2 a b" or something, sscanf would return a short item count.
As others have noted, if you know how many numbers to expect, sscanf is the easiest solution. Otherwise, the following sketches a more general solution:
First tokenize the string by spaces. The standard C method for this is strtok():
char* copy;
char* token;
copy = strdup(string); /* strtok modifies the string, so we need a copy */
token = strtok(copy, " ");
while(token!=NULL){
/* token now points to one number.
token = strtok(copy, " ");
}
Then convert the string to integers. atoi() will do that.
If the string always contains 4 numbers delimited with spaces, then it could be done with sscanf:
sscanf(string, "%d %d %d %d", &a, &b, &c, &d);
If the count of numbers varies, then you would need to parse the string.
Please clarify your question accordingly.
sscanf() can do that.
#include <stdio.h>
int main(void)
{
int a, b, c, d;
sscanf("1 2 3 4", "%d %d %d %d", &a, &b, &c, &d);
printf("%d,%d,%d,%d\n", a, b, c, d);
}

Resources