Error with ToString() - c

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.

Related

Get the return value from a function

I want to modify a char by using a function and print it on the screen but my code cannot achieve this function. Here is my source code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
long M = 2147483647;
void IntroduceError(char k[],double p)
{
int i;
for ( i = 0; i < 8; i++) {
if ((double)random()/M <= p)
k[i] = 1;
}
}
int main(int argc, char *argv[])
{
char test[] = "11110000";
double rate = atof(argv[1]);
IntroduceError(test, rate);
printf("\nErrored codeword is : %s\n",test);
return 0;
}
k is a string i.e. array of characters, but you're assigning an integer value to it.
Instead of:
k[i] = 1;
You probably want:
k[i] = '1';
Also, you should call srandom at the start of your program to seed the random number generator, passing in at least the PID, i.e. srandom(getpid()); so that you don't get the same results every time.
get in the printf statement is not defined. If you change get with test it should compile.

Problems in Project Euler #8

I have been working on Project Euler lately. I am programming in C and have a query related to Problem 8. The question is:
Find the greatest product of five consecutive digits in the 1000-digit number.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
Here is my own done work yet:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *string = "731671765313306249192251196744.............";
char *x;
x = string;
for(int counter = 0;counter < 2;counter++)
{
printf("%s\n", x + strlen(x) - 5);
x = x + strlen(x) - 5;
}
}
SO, the problem is that unable to understand what to do next. I am able to extract the digits, but what would be the algorithm to use these digits and create an algorithm thats fast and efficient. So, any help, please! Another problem is that when I try to convert the char to an int value, it fails and gives the error "error: incompatible pointer to integer conversion initializing 'char' with an expression of type'char[1001]'. I have used the methods to convert values as here:Coversion of char to int, and so thats it. If any more suggestions, please suggest the better things...
You can read the characters in the string, convert them to integers and then find their product to check which group of 5 consecutive integers give the highest product. At the loss of fun and learning that you can have trying to do it yourself, you can try this.
#include <stdio.h>
#include <string.h>
// calculates the product of a group of numeric chars
// after converting them to int type
int gproduct(char *s, int glen) {
int i = 0;
int val = 1;
// convert a numeric char to int value by subtracting '0'
// assuming the chars are encoded in ascii. consider using
// the standard library function atoi for portability.
while(i < glen)
val *= (s[i++] - '0');
return val;
}
int main(void) {
char *numstr = "731671765313306249192251196744.............";
int glen = 5; // group length
int maxcount = strlen(numstr) - glen;
int maxval = gproduct(numstr, glen); // initialize maxval
int tempval;
for(int i = 1; i < maxcount; i++) {
tempval = gproduct(numstr + i, glen);
if(tempval > maxval)
maxval = tempval;
}
printf("%d\n", maxval);
return 0;
}

Why my code is printing an heart at printf?

This is my code:
#include<stdio.h>
#include<stdlib.h>
main(){
char *alf="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$%&.",text[64];
int i, alfl=69;
srand(time(0));
for(i=0;i<64;i++)
text[i] = *(alf+rand()%alfl);
printf("%s",text);
}
But at the printf function it print an heart at final of the string.
As others have suggested in the comments (#mbratch and #KerrekSB) you need a null terminator at the end of your string.
Modify your code as follows:
#include<stdio.h>
#include<stdlib.h>
main(){
char *alf="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$%&.",text[64];
int i, alfl=69;
srand(time(0));
for(i=0;i<63;i++)
text[i] = *(alf+rand()%alfl);
text[i] = '\0';
printf("%s",text);
}
And it should work, but as #Simon suggested there can be other things that could help improve your code and understanding of C.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 64
int main() { // If you don't add a return type, int is assumed. Please specify it as void or int.
const char *alf="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$%&."; // This string cant be assigned to. Make sure that you stay "const-correct".
char text[LEN]; // Please avoid magic numbers here too by using a constant
int i, alfl = strlen(alf); // As #Simon says, it is better to not use magic constants.
srand(time(0));
for(i=0;i<LEN-1;i++)
text[i] = *(alf+rand()%alfl);
text[i] = '\0'; // make sure to null terminate your string.
printf("%s",text);
return 0; // If your return type is int, you must return from the function.
}
Several suggestions:
main should return an int:
int main(void)
{
return 0;
}
You should use strlen to determine the length of strings:
alfl = strlen(alf);
It's easier to use array notation:
for(i = 0; i < 64; i++)
text[i] = alf[rand() % alfl];
If you use text like a string, it must be '\0' terminated:
text[63] = '\0';

Beginner Here Rand in c

im a 1st grader when it comes to c and need help with storing 5 random values in an array and outputting them. Heres where am at.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
struct score_card {int A_ones; int B_twos; int C_threes; int D_fours; int E_fives; int F_sixes; int G_chance;};
int dice_rolls[5];
int randomize(void);
int value;
int main(void) {
struct score_card test;
randomize;
int i;
for(i = 0; i <= 4; i++){
printf("%d\n", dice_rolls[i]);
}
printf("\n");
return 0;
}
int randomize(void){
int i;
srand(time(0));
for(i = 0; i <= 4; i++){
value = rand() % 6 + 1;
dice_rolls[i] = value;
}
}
The output is :
6294304
6294308
6294312
6294316
6294320
the goal was to use modular division to get values from 1 -->6 and store them in the dicerolls array.
I see two immediate problems.
First. you're not terminating your random numbers with a newline. That's why they're all strung together in a big sequence. Change your output line to:
printf("%d\n", &dice_rolls[i]);
Secondly, you're not actually calling randomize. The correct way to call it is with:
randomize();
The statement randomize; is simply an expression giving you the address of the function. It's as useless in this case as the expression 42; which also does nothing. However it's valid C so the compiler doesn't necessarily complain.

Sorting strings with C

My aim is to write an app which generates an char - array (each should be random-filled with strings of the length 4) and sorts this array. The time this process takes should be measured. I coded the following:
#include <string.h>
#include <jni.h>
#include <time.h>
#include <math.h>
clock_t start, finish;
static int ARRAY_LENGTH = 200;
static int WORD_LENGTH = 4;
char values[200];
void sortStringArray(void){
int i, j;
for(i = 0; i < ARRAY_LENGTH; i++){
for(j = 0; j < ARRAY_LENGTH-1; j++){
if(strcmp(values[j], values[j+1]) > 0) {
char holder = values[j+1];
values[j+1] = values[j];
values[j] = holder;
}
}
}
}
char generateRandomChar(char aC[]){
int length = strlen(aC);
char randStr[WORD_LENGTH];
int m;
for(m = 0; m <WORD_LENGTH; m++){
int randNr = rand()%length;
randStr[m] = aC[randNr];
}
return randStr;
}
void fillStringArray(void)
{
char allowedChars[] = "abcdefghijklmnopqrstuvwxyz";
int k;
for(k = 0; k < ARRAY_LENGTH; k++){
char randStr = generateRandomChar(allowedChars);
values[k] = randStr;
}
}
double
Java_com_example_hellojni_HelloJni_processStringSort( JNIEnv* env, jobject thiz)
{
start = clock();
fillStringArray();
sortStringArray();
finish = clock();
return ((double)(finish - start));
}
Since I am pretty new to coding C, i am not that fimilar with the concept of pointers, and therefore i recieve some mistakes.
alt text http://img38.imageshack.us/img38/2894/androidndkdebugc.jpg
It would be helpful if sb could explain me where it would be useful to use a pointer in this code. Some help with the errors would be very appreciated.
Thanks! Ripei
Without re-writing your code from scratch, it is difficult to to know where to start. I'm afraid it is all wrong. In order to get a good understanding of pointer and character string use in C, you must read a good, authoritative book on the language, Luckily, C has one of the best such books in the world - The C Programming Language. If you haven't already got a copy, get one, and if you have, re-read the chapters on pointers and strings.
Well for one thing you seem to think that char means string.... sometimes? char means a character, a number between 0 and 255. As the warnings on line 15 say, values[j] and values[j+1] are not strings (char *), they are characters (char). You probably want to make values an array of strings, ie an array of arrays of characters.
The 2nd set of warnings you're getting are related to line 31, where you're returning an array of characters (a pointer) from a function that states that it returns a character. The compiler silently casts the pointer to a character (since a pointer is a number) and returns that. You'll end up with a random number, which is probably not what you want.
To fix this you'll have to make the function return a char *, but there's a catch. randStr is gone as soon as you get out of the function, thus making it impossible to return. You could use strdup to duplicate the string and, after you're done using it in your main function, you call free to get rid of it.
While we're on this function, the parameter to it should be a char *, not a char[]. They have different meanings.
The last message (the only error reported as such apparently) is because you didn't define rand(). Adding a #include <stdlib.h> at the beginning of the program should fix it.
Thank you very much Blindy for your hints. I tried to implement your hints. Now the program doesn't throw errors but the problem is that i can't check if the operation is done correctly with the programm-environment i've to work with. Do you think the code is correct as it is shown below? Also the time it takes is quite less: 11ms. Do I calc this right?
Neil Butterworth,... well your're probably right, but I had to start somehow... and I tried my best to do so.
Vinko Vrsalovic,... well you're not right ;) I did it step by step but I thought that its better to show you the whole program and all errors at one time.
#include <string.h>
#include <jni.h>
#include <time.h>
#include <stdlib.h>
long start, finish;
static int ARRAY_LENGTH = 500;
static int WORD_LENGTH = 4;
static int LOOPS = 10;
char *values[1000];
static long getTime(void){
struct timeval now;
gettimeofday(&now, NULL);
return (long)(now.tv_sec*1000 + now.tv_usec/1000);
}
void sortStringArray(void){
int i, j;
for(i = 0; i < ARRAY_LENGTH; i++){
for(j = 0; j < ARRAY_LENGTH-1; j++){
if(strcmp(values[j], values[j+1]) > 0) {
char *holder = values[j+1];
values[j+1] = values[j];
values[j] = holder;
}
}
}
}
char* generateRandomChar(char *aC){
int length = strlen(aC);
char randStr[WORD_LENGTH];
int m;
for(m = 0; m <WORD_LENGTH; m++){
int randNr = rand()%length;
randStr[m] = aC[randNr];
}
return strdup(randStr);
}
void fillStringArray(void)
{
char *allowedChars = "abcdefghijklmnopqrstuvwxyz";
int k;
for(k = 0; k < ARRAY_LENGTH; k++){
char *randStr = generateRandomChar(allowedChars);
values[k] = randStr;
}
}
jlong
Java_com_example_hellojni_HelloJni_processStringSort( JNIEnv* env, jobject thiz)
{
start = getTime();
int i;
for(i = 0; i < LOOPS; i++){
fillStringArray();
sortStringArray();
}
finish = getTime();
return (finish - start);
}

Resources