How to concatenate number in printf - c

I would to do something like this:
int index=1;
for(index=1; index<10; index++)
printf("Welcome player"+index+". How are you today?");
I'm new in C programming and not sure how to concatenate an integer.

printf() has special format specifiers that enables you to inject variables into the resulting string. In your case you would want to do it like this:
printf("Welcome player %d. How are you today?", index);
See more info here.

what I think you are trying to do is this
char index[20];
printf("Enter Name: ");
scanf("%s", index);
printf("Welcome player %s How are you today?", index);
The reason we do the scanf is because we want user input, whatever the user will put in the scan f will come out as the output for your printf.
We use %s because index is a string, for things such as ints, floats, and chars you use %d, %f, or %c or else it wouldn't compile if you were trying to use %d if it was actually a string
at the end of the second printf we used the name of the integer we wanted to use, show the value within the string would print.
The array with the char index[20]; is to assume that the string will not be longer than twenty bits, if you wanted more than you can write however long you wish it to be, if you want it less you can write it to be small as 0 if you wished. (This would give it eight character input, because a byte can store 8 bits, so 8 characters).

Related

Formatted input in C

Can someone please help tell me what is wrong with my code. I am trying to ask user fro two name of his/her friends and their age. then return the average of their ages. but the output is not as expected.
#include <stdio.h>
int main(void){
char friend1;
char friend2;
float age1;
float age2;
float average;
printf("Please enter name of your friend...\n");
scanf("%s", &friend1);
printf("How old is %s?\n",&friend1);
scanf("%f", &age1);
printf("Enter name of one more friend!\n");
scanf("%s",&friend2);
printf("How old is %s?\n", &friend2);
scanf("%f", &age2);
average = (age1+age2)/2;
printf("Average age of your friends %s and %s is %4.2f years old\n" ,&friend1,&friend2,&average);
return 0;
}
Two things -
In C strings are basically null terminated char arrays.
You need to have enough memory to hold the inputted characters and the '\0' to mark the end of the string.
You have used one char variable and passed it's address to scanf. scanf tries to store the input name but it will access some memory that it shouldn't resulting in undefined behavior.
The correct way would be to use an array with some number maximum char that might be there. You will do the same thing for friend2 variable also.
#define MAXLETTERS 10
char friend1[MAXLETTERS ];
if( scanf("%9s",friend1) == 1){
// got name in friend1
}
Notice the %9s - why 9? Because we will get 9 characters from input and the last one (10th one) will be the \0 character. The problem with scanf("%s",friend1) is %s matches any string, of any length, and scanf() has no idea when to stop reading. It reads as long as it can parse the input according to the format string, as a result it writes to friend1 more than 10 characters - leaving us with a possibility of buffer overflow.
By specifying that 9 we are telling scanf don't read more than 9 characters.
& operator when applied to variable returns the address of it - in your case after calculating the average of two friend's, you need to print it's value not it's address. So remove & in printf for the 3 variables listed in each of the cases. Just pass the value of the variables to the printf function not the addresses.
In case you are wondering why there is no & used in scanf with friend1 and friend2 - then you should know that when an array is passed to a function (here that function being scanf) it is converted into (known as array decaying) pointer to the first element. The first element here is friend1[0] and a pointer to it means that pointer's content is &friend1[0]. And that is what is being expected by scanf - the address where it will store the inputted data.
Declare friend1 & friend2 as char array if you want to store names into them as below
char friend1[50];/** take the char array of required size **/
char friend2[50];
And while scanning you no need to provide & in scanf if friend1 is declared as char array, because char array name itself address.
printf("Please enter name of your friend...\n");
scanf("%s", friend1);
Apply the same for friend2. Also while printing don't use & if you want to print value of average.
Replace
printf("Average age of your friends %s and %s is %4.2f years old\n" ,&friend1,&friend2,&average);
with
printf("Average age of your friends %s and %s is %4.2f years old\n" ,friend1,friend2,average);
Since scanf requires a string (pointer to char), try switching to an array of char.
char friend1[20];
char friend2[20];
May be a valid example if the strings are less than 19 characters.

Interactive, randomized program in C

My goal with this program is to incorporate the users inputs into a sort of interactive/randomized story but I'm not sure how I'm supposed to get the inputs from the users to fit between *ptrDescription, *ptrBeginning, *ptrMiddle, and *ptrEnd. Any help would be much, much appreciated!
#include <stdio.h>
#include<stdlib.h>
#include<time.h>
#include <string.h>
#include <ctype.h>
int main(void){
int i;
char name[20];
char color[20];
int age;
char sentence[1];
//array of pointers to char arrays
char *ptrDescription[]={"the painfully handsome","the one and only","who seemed much older than"};
char *ptrBeginning[]={"was blissfully ignoring","could clearly see","had no idea"};
char *ptrMiddle[]={"the huge truck","the falling meteor","the bucket of milk","the mailman","the most powerful wizard"};
char *ptrEnd[]={"that was barreling toward them.","on the horizon."};
srand(time(NULL));
printf("Enter your first name: ");
scanf("%s", &name);
printf("\nEnter your age: ");
scanf("%d", &age);
printf("\nEnter your favorite color: ");
scanf("%s", &color);
for (i = 0; i < 1; i++)
{
//strcpy(sentence,ptrDescription[rand()%3]);
//strcat(sentence," ");
//strcat(sentence,ptrBeginning[rand()%3]);
//strcat(sentence," ");
//strcat(sentence,ptrMiddle[rand()%5]);
//strcat(sentence," ");
//strcat(sentence,ptrEnd[rand()%2]);
//strcat(sentence,".");
//sentence[0]=toupper(sentence[0]);
puts(sentence);
}
getch();
return 0;
}
EDIT:
I've edited a section of my code so that directly following for (i = 0; i < 1; i++) it now looks like this:
snprintf(sentence, sizeof sentence,"%s, %s %d year old, %s %s %s %s", name, ptrDescription[rand()%3], age,ptrBeginning[rand()%3], ptrMiddle[rand()%5], ptrEnd[rand()%2]);
There are tons of strange characters after the sentence in the output, like Japanese characters and stuff. I'm not sure why they're there, though. This is what it looks like exactly:
"Enter your first name: Justin
Enter your age: 20
Justin, the arrogant 20 year old, was purposefully ignoring the most powerful wizard that was barreling toward them. 汽$0HβHζ(テフフフフフフフフフフフフフH・(DキHH広$0陏&・汽$0タHζ(テフフフフフフフフフフフフフフフH WH・ H櫛H・t9HνHテ<"
Anyone know how I can get rid of them?
If you already have a name and an age, it's just a matter of inserting them into the correct place in sentence, right? So strcat(sentence, name) would work for name. age is a little trickier since you have to format the number first, and strcat won't do it for you. One solution would be to use sprintf(buf, "%d", age), and then concatenate buf (which is a scratch char array you would have to declare).
Any time you work with strings in C, you have to be concerned about having enough space in the target buffer. Your program can run out of space during both input and output. For the output, I would get rid of sentence altogether; since you just end up writing to stdout I would printf("%s", [part]) each part as you go along. For reading, scanf supports adding a length argument to the format string.
If you use one of the *printf functions, there are 2 things you must be careful about:
The arguments you pass are correct for the format string you use
Your buffer ends up null-terminated
Your current problem is with #1 - your format string promises 7 arguments to follow, but you only supply 6. snprintf grabs a "random" 7th value from the stack, interprets it as a char pointer, and copies whatever it finds there to sentence. You could see similar problems if your format string promised a char pointer but you placed an int in a given position. In this case the format string is a constant, so a smart compiler can validate that your format string matches the subsequent parameters. You'll want to get into the habit of taking compiler warnings seriously and not ignoring them.
The second point could be an issue if your sentence ended up bigger than your sentence buffer. If there is no room for a null-terminator, one won't be applied. You can check the return value of snprintf, or you can defensively always write a 0 to the last array position.

problems with scanf and conversion specifiers

Here you can see my source code:
#include <stdio.h>
int main()
{
char yourname;
char yoursex;
int yourage = 0;
printf("Hey, what's your name?\n");
printf("My name is: ");
scanf("%s", &yourname);
printf("Oh, hello %s! \n\n", &yourname);
printf("Are you a boy or a girl?: ");
scanf("%s", &yoursex);
printf("Nice to know you are a %s! \n\n", &yoursex);
printf("How old are you %s? I am ", &yourname);
scanf("%d", &yourage);
printf("I see you are %d, you have many years then!", &yourage);
return 0;
}
I was trying things that I didn't knew, and strangely it is not working for me. What's the problem? Also, why it needs to be %s and not %c? If I use %c instead it does not work!
Where it says:
How old are you %s? instead of putting my name, it says ''oy''
and instead of showing my age in the last line, it shows a big number.
These are the very basics of C Programming, and I strongly advise you to get a decent book - The C Programming Language by Dennis Ritchie would be a good start.
There are numerous errors in your code.
A char can contain only one character, like 'A', or 'a' or something like that. When you're scanning a name, it is going to be a group of characters, like 'E', 'd', 'd', 'y'. To store multiple characters, you need to use a character array. Also, the format specifier used to scan/print characters is %c, %s is for when you need to scan a group of characters, also called a string into an array.
When you use printf, you do not supply a pointer to the variable you are trying to print (&x is a pointer to variable x). The pointer is a 32/64-bit integer, which is likely why you see a random integer when trying to print. printf("%c\n", charVar) is sufficient.
scanf does not need an & while using %s as the format specifier, assuming you have passed a character array as the argument. The reason is, scanf needs to know where to store the data you are reading from the input - and that is given by a pointer to the memory location. When you need to scan an integer, you need to pass an &x - which means, pointer to memory location of x. But when you pass a character array, it is already in the form of a memory address, and doesn't need to be preceded by an ampersand.
I once again recommend you look up some decent tutorials online, or get a book (the one I mentioned above is a classic). Type the examples as given in the material. Experiment. Have fun. :)
%s is for reading a string -- multiple characters delimited by whitespace. %c is for reading a single char.
You declare your yourname and yoursex vars as characters, and then try to read strings into them. The string read will overwrite random other things in the stack frame and misbehave or crash.
You want to declare yourname and yoursex as character arrays, so they can hold strings:
char yourname[32];
char yoursex[32];
then, when reading into them, you want to include a length limit so they don't overflow:
scanf("%31s", yourname);
This is a single character:
char yourname;
But %s indicates that the variable is a string (i.e., an array of characters terminated by a NUL). That's why you need %c. If you really did mean to use a string, then define the variable like
char yourname[32]; /* just pick a big enough size */
Also, you are correct to use the address of the variable with scanf(), but printf() needs the value. So instead of
printf("I see you are %d, you have many years then!", &yourage);
use
printf("I see you are %d, you have many years then!", yourage);
The "big number" is the memory address.
Make sure you read the comments in code!
#include <stdio.h>
int main()
{
char yourname[10];
char yoursex[5]; // boy or girl + null terminator
int yourage = 0;
printf("Hey, what's your name?\n");
printf("My name is: ");
scanf("%s", &(*yourname)); // & and * cancel each other out,
// thus take a look at the next scanf()
printf("Oh, hello %s! \n\n", yourname); // yourname is now an array
printf("Are you a boy or a girl?: ");
scanf("%s", yoursex);
printf("Nice to know you are a %s! \n\n", yoursex);
printf("How old are you %s? I am ", yourname);
scanf("%d", &yourage); // ok
printf("I see you are %d, you have many years then!", yourage); // here you don't
// need the address of the variable!
return 0;
}
The expression char yourname; only holds space for a single character, so quite likely you end up corrupting the memory space when scanning for yourname. You should allocate a bigger buffer and make sure that you don't overrun its length by setting a maximum number of characters to be read with the scanf function; as described in some of the other answers.
The fact that the following printf print correctly the name doesn't mean that the memory doesn't get corrupted; as C/C++ don't really check the boundary of any strings or arrays used at runtime.
As suggested by others, starting by reading a good book about C and/or C++ wouldn't a bad idea.

Printing partial char arrays...with a twist

So I know there are a lot of questions about printing only segments of char arrays in C and I have read them and though my question is similar in nature, there is a small twist to mine. Given my code below, how do I only print out the first four characters of my fmt array? I am not allowed to alter fmt so therefore I must use VAL to specify that I just want to print the value, the new line, and one space.
#define VAL 4
int main() {
char fmt[10] = "%d\n ";
int value = 1;
printf(fmt, value);
}
EDIT:
This is just a fraction of my code because I felt this was all that was necessary. If more is needed I will provide the rest of my code.
EDIT2:
Restrictions:
No new variables & must use VAL to specify how much of the fmt array to be printed.
EDIT3 (FULL QUESTION):
Fill in the missing part of the program, without adding any variable declarations. Ask the user to choose how s/he wants to print the entered integer value. (Look up the integer format specifiers for printf if you don't know them all.) Using the indicated format specifier letter print the integer that was entered earlier, followed by a return, and then reprompt for another format letter (though not for a new integer).
Getting under the complexity limit is a major part of the challenge. Be flexible about which type of loop you choose, and how you read in the format-specifier character. Also, note that scanf skips whitespace when reading a character, if there is a blank before the %c in the format string. And, there is an important use for that VAL define, involving getting rid of spurious blanks in the output. And finally, don't even think about doing this with a big switch or if-else block.
#include <stdio.h>
#define VAL 4 // You might want this
int main() {
char fmt[10] = "%d\n "; // Quickly initializes fmt array
int value;
printf("Enter an integer: ");
scanf("%d", &value);
//from here below is my code, above code is pre-provided
printf("Enter a format specifier (x, X, c, d, i, o, or q to quit): ");
scanf(" %c", &fmt[1]);
while (fmt[1] != 'q') {
printf("%4s", fmt, value);
printf("Enter a format specifier (x, X, c, d, i, o, or q to quit): ");
scanf(" %c", &fmt[1]);
}
}
how do I only print out the first four characters of my fmt array
How about:
printf("%4s", fmt);
It doesn't work because I need the variable value to tell the %d in
fmt what to print out
Options:
Print to a separate string (snprintf) using a length of 4
Process your number until it contains the appropriate number of digits and then print
Adding to cnicutars very good answer, I'd just like to point out that if the array isn't const, you can alter it:
char saved = fmt[4];
fmt[4] = '\0';
printf (fmt, value);
fmt[4] = saved;
Edit
As I specified in my original question, the array cannot be altered.
Yes, well... I misread and thought the original const format string cannot be altered. Nevertheless, I think this tidbid of information can be useful to someone else.
After reading value from input then print could be:
printf("%.*s", VAL, fmt, value);

Is there a way to read a c-string and then an int with a single scanf in C?

Hey,
I'm trying to get this function to get the following output with the listed input, the "..." is where I'm not sure what to write:
void Question8(void)
{
char sentence[100];
int grade;
scanf(….);
printf("%s %d", sentence, grade);
}
Input:
My CS Grade is 1000
Output:
My CS Grade is 100
However, the kicker is that I need the scanf to read a c-string and then an int with a single scanf command, is this even possible?
Edit:
I can only edit the code in the location with the three periods ( "..." ), I cannot use anything more. I can assume that the input listed is expected but I cannot change anything outside of the three periods.
The output does not contain typos, the purpose of this assignment is to use flags and escape sequences.
It is possible to read pre-formatted string using scanf, however the format must be strict.
This version will continue to read the input until a digit is encountered and then read an integer.
Here is your code again:
char sentence[100];
int grade;
scanf("%[^0-9] %d",sentence,&grade);
printf("%s %d\n", sentence, grade);
I'll get this over with quick:
<obligatory_rant>
stupid question, but I guess it's homework and you're
stuck with these absurd limitations
</obligatory_rant>
Then, if you need to read everything up to but excluding the first digit, then the number:
if (scanf("%100[^0-9] %3d", text, &number) == 2)
...
Notes:
100 in "%100[... should be whatever your actual buffer size is to protect against buffer overrun.
The %3d documents that at most 3 digits should partake the the numeric value, so 1000 is correctly read as 100.
[^...] means the string made up of characters not ("^") in the following set, which is then specified as 0-9 - the digits.
if (... == 2) tests whether both positional parameters were scanned / converted successfully.
If you can't add an if and error message, then simply:
scanf("%100[^0-9] %3d", text, &number)
Tested in Visual Studio 2008
#include <stdio.h>
int main()
{
char sentence[100];
int grade = 0;
scanf("%[^0-9] %d",sentence,&grade);
printf("%s %d", sentence, grade);
return 1;
}
Input :
My CS Grade is 100
Output :
My CS Grade is 100
This is a really horrible question. A correct set of scanf parameters would be "%14c%3d", sentence, &grade
Because a space is included in the printf statement the trailing space needs to not be stored in sentence. Because the input contains other spaces there is no other solution (that I can thing of) than a fixed length. The integer parsing also requires a fixed length to truncate 1000 to 100.
I can think of no reason to ever write code anything like this. The code fits the requirements but wouldn't be useful in any other circumstances. I think that this is a very poor training exercise.

Resources