All I simply want to do is a make a record that starts with C or D randomly and has a number along with it 1-10. so a record would be C10. Can anyone tell me what I am doing wrong here?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
/*
*
*/
int main(int argc, char** argv)
{
char letter[] = { 'C', 'D' };
char record[2];
int r=1;
while (r < 11)
{
char num;
num = r;
record = (letter[rand()%2],num);
r++;
}
return 0;
}
For one obvious point, "C10" requires 4 characters, assuming you want it as a normal C string (3 in the string + 1 NUL terminator) but you've only made room for 2.
At least assuming you want your 1-10 as text characters, you'd typically want to do something like:
sprintf(record, "%c%d", letter[rand()%2], num);
Not that it matters a lot, but you seem to be including a lot of unnecessary headers for what you're doing.
record = (letter[rand()%2],num);
This is not a legal opporation... try this:
record[0] = letter[rand()%2];
record[1] = num;
You want the characters '0'-'9' popping up, but you are assigning the character r a numerical value between 0 and 10. Check out the table of ASCII characters.
I'd try it like this:
char record[4];
for (unsigned r = 0; r <= 10; ++r) {
snprintf(record, sizeof(record), "%c%d", letter[rand() % 2], r);
}
Related
I usually use printf("%-8d",a); for example for 8 spaces after (and including) an integer.
My code:
#include <stdio.h>
#include <string.h>
int main()
{
int a = 10;
char b = "Hello";
}
How can I print: '#10-Hello '
with 16 spaces (8 is the integer and the string, and 8 spaces after)?
Do it in two steps. First combine the number and string with sprintf(), then print that resulting string in a 16-character field.
int a = 10;
char *b = "Hello";
char temp[20];
sprintf(temp, "#%d-%s", a, b);
printf("%-16s", temp);
A tab is 8 spaces, so, you can add \t\t
The below is a super basic way to print what you wanted.
printf('#' + a + '-' + b + '\t\t');
I'm not as familiar with the syntax of C so it may be :
printf('#', a, '-', b, '\t\t');
Also, as mentioned in a previous answer, "Hello" is not a char but either an array of char or a String.
#include <stdio.h>
#include <string.h>
int main()
{
int a = 10;
char b[] = "Hello";
printf("#%d-%-17s",a,b);
}
this should get the job done, adjust your spacing as needed
Could do this with 2 printf()s. Use the return value of the first to know its print length, then print spaces needed to form a width of 16. No temporary buffer needed.
#include <assert.h>
#include <stdio.h>
int main(void) {
int width = 16;
int a = 10;
char *b = "Hello"; // Use char *
int len = printf("#%d-%s", a, b);
assert(len <= width && len >= 0);
printf("%*s", width - len, ""); // Print spaces
}
I'm new to c. Please help me
Why do I get this error using eclipse
Multiple markers at this line
- request for member 'ToString' in something not a structure or union
- Method 'ToString' could not be resolved
Here is my code
#include <stdio.h>
int main()
{
int s = 5;
int n = 4;
char g = s.ToString();
char l = n.ToString();
printf(g+l);
return 0;
}
s and n are just ints; they don't have a ToString() method. Also, as #remyabel pointed out, char is not the appropriate type for storing a string value, anyway; it stores only one character.
You don't need to convert your ints to strings at all to do what you're trying to accomplish, so you actually want something like this:
#include <stdio.h>
int main()
{
int s = 5;
int n = 4;
printf("%d%d", s, n); // you can't add l to g here!
return 0;
}
// output 54
DEMO
Oh, and please use more descriptive variable names!
EDIT: To save the string, as requested in the comments, you could do this:
char myString[10];
sprintf(myString, "%d%d", s, n); // myString is now "54"
I'd suggest picking up a C tutorial and starting from the beginning. The use of ToString isn't the only thing that's wrong. You could rewrite it this way and it should work (assuming you want to print "54"):
#include <stdio.h>
int main()
{
int s = 5;
int n = 4;
char g = '0' + s;
char l = '0' + n;
printf("%c%c", g, l);
return 0;
}
But this only works as long as s and n are less than 10, and besides is overly complicated since printf is made for formatting and printing values of different types. This would work just as well:
#include <stdio.h>
int main()
{
int s = 5;
int n = 4;
printf("%d%d", s, n);
return 0;
}
If you want to use the string for something else than printing, the answer depends on what you want to do.
i have the next code, in which i have a string "hello world" and it has to convert each character into its ASCII value, but instead of printing [68656C.....] it prints some white spaces right after the '[', like this [......68656C]. And i canĀ“t find the reason why
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i,lon;
char *cod_maq,*c = {"hello world"},c[2];
lon = strlen(c);
cod_maq = (char*)malloc((lon+1)*sizeof(char));
for(i = 0;i < lon;i++)
{
sprintf(c,"%X",c[i]);
strcat(cod_maq,c);
}
printf("[%s]\n",cod_maq);
return 0;
}
thanks
The memory in your malloc already contains data that you need to reset.
malloc allocates memory it doesn't initialize it, so you just get random garbage that was there previously.
memset(cod_maq, 0, size_of_cod_maq)
sprintf(c,"%X",c[i]); : very bad.
fix to like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int i,lon;
char *cod_maq, *c = {"hello world"};
lon = strlen(c);
cod_maq = (char*)malloc((lon*2 + 1) * sizeof(char));//2 required per character
for(i = 0; i < lon; i++){
sprintf(cod_maq + i*2, "%02X", c[i]);
}
printf("[%s]\n", cod_maq);
free(cod_maq);
return 0;
}
I'm doing the CS50x class and I am stuck at a glitch. I asked them what was going on and no one knew what was going on.
Whenever I try to print a lowercase f it always comes up as ?. Try doing 23 as the argument and abcdefghijklmnopqrstuvwxyz as the input. It's messed up. Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main (int argc, string argv[]){
if(argc !=2){
return 1;
}
string x = GetString();
int key = atoi(argv[1]);
for(int a = 0, n = strlen(x); a < n; a++){
char i = key + x[a];
if(islower(x[a])){
if(i > 122){
i = (i-122) + 96;
}
}
if(isupper(x[a])){
if(i > 90){
i = (i-90) + 64;
}
}
printf("%c", i);
}
printf("\n");
return 0;
}
I suspect it's because your char i defaults to signed. When you add 23 to a lowercase letter, anything that is above 104 (being 127-23) is going to wrap around into negatives. Looking at your code, it will stay negative because it fails the subsequent tests and does not get modified.
It's usually best to do char arithmetic with int, then convert back to char... But you could probably fix this by using unsigned char.
I'm trying to create a char array made of some letters and numbers (the function was way more complex initially but i kept simplifying it to figure out why it doesn't work properly). So i have a char array in which i put 2 chars, and try to add some numbers to it.
For a reason i can't figure out, the numbers do not get added to the array. It might be really stupid but I'm new to C so here's the simplified code. Any help is much appreciated, thanks!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char some_string[20];
char *make_str() {
some_string[0] = 'a';
some_string[1] = 'x';
int random = 0;
int rand_copy = 0;
random = (rand());
rand_copy = random;
int count = 2;
while ( rand_copy > 0 ) {
rand_copy = rand_copy / 10;
++count;
}
int i=2;
for (i=2; i<count; i++) {
some_string[i] = random%10;
random = random/10;
}
return (some_string);
}
int main(int argc, const char *argv[]) {
printf("the string is: %s\n",make_str());
return 0;
}
You have many problems:
resulting string is not zero-terminated. Add some_string[i] = '\0'; to fix this
character (char) is something like "a letter", but random % 10 produces a number (int) which when converted to character results in control code (ASCII characters 0-9 are control codes). You'd better use some_string[i] = (random % 10) + '0';
you're using fixed length string (20 characters), which may be enough, but it could lead to many problems. If you are a beginner and haven't learn dynamic memory allocation, than that's ok for now. But remember that fixed-length buffers are one of top-10 reasons for buggy C-code. And if you have to use fixed-length buffers (there are legitimate reason for doing this), ALLWAYS check if you are not overrunning the buffer. Use predefined constants for buffer length.
unless the whole point of your excercise is to try converting numbers to strings, use libc function like snprintf for printing anything into a string.
don't use global variable (some_string) and if you do (it's ok for a small example), there is no point in returning this value.
Slightly better version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUF_LENGTH 20
char some_string[BUF_LENGTH];
char *make_str() {
some_string[0] = 'a';
some_string[1] = 'x';
int random = rand();
int rand_copy = random;
int count = 2;
while (rand_copy > 0) {
rand_copy = rand_copy / 10;
++count;
}
int i;
for (i = 2; i < count; i++) {
/* check for buffer overflow. -1 is for terminating zero */
if (i >= BUF_LENGTH - 1) {
printf("error\n");
exit(EXIT_FAILURE);
}
some_string[i] = (random % 10) + '0';
random = random / 10;
}
/* zero-terminate the string */
some_string[i] = '\0';
return some_string;
}
int main(int argc, const char *argv[]) {
printf("the string is: %s\n",make_str());
return 0;
}