I know that getline is C++ standard but I need to read a line of digits:
123856
and save it to an array. But how to do this without spaces between given (as input) digits? I want a user input to be:
123856 (with no spaces) and then save it to an array (n element array) and after that, I want my array to look like this:
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 8;
array[4] = 5;
array[5] = 6;
But how to make it in C, without a getline?
This is NOT what I want:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
int main(int argc, char **argv)
{
int t[4];
int i;
for(i=0; i<4; i++)
scanf("%d", &t[i]);
for(i=0; i<4; i++)
printf("%d\n", t[i]);
return 0;
}
If I understood you correct, the following should do it:
read the whole line
loop through the string as long as you get digits or the string ends
for every digit, place it's value in your array and increase the index by 1
while( ( c = getchar()) != EOF && c != '\n' && i < max ) {
/* If desired, add check for value outside of 0-9 */
array[ i++ ] = c - '0';
...
}
char arr[] = "1234567";
int intarr[10];
int count = 0;
for (char* ptr = arr; *ptr; ptr++) {
intarr[count] = *ptr - '0';
count++;
}
try this
#include <stdio.h>
#include <string.h>
main (int argc, char *argv[])
{
FILE *f;
int i=0;
int j=0;
char output[100];
char* output1[100];
char string[100];
char delims1[] = " ";
char delims2[] = "*";
char* result = NULL;
char* result3 = NULL;
int num;
//for (j=0; j<2; j++)
//{
//printf("%s",delims9[6]);
//}
f = fopen("text.txt","r");
//
while( fgets(string,sizeof(string),f) )
{
result = strtok( string, delims1 );
while( result != NULL )
{
output1[i]=result;
printf("%s\n",output1[i]);
result = strtok( NULL, delims1 );
i++;
}
for (num = 0; num < 100; i++ ) //
{ // Error On this array
printf("%s\n", output1[i]); //
} //
}
printf("\n%d",i/3+1);
return 0 ;
}
Ok, without using any string.
int digits = 123856;
int numofdigits = 1 + floor(log10(digits));
int digits_arr[numofdigits];
int i;
for(i = numofdigits-1; i >= 0; i--) {
digits_arr[i] = (int)floor(digits / pow(10, i)) % 10;
}
Try the below link... Same question asked here and get solution....
convert an integer number into an array
char * convertNumberIntoArray(unsigned int number) {
unsigned int length = (int)(log10((float)number)) + 1;
char * arr = (char *) malloc(length * sizeof(char)), * curr = arr;
do {
*curr++ = number % 10;
number /= 10;
} while (number != 0);
return arr;
}
Related
Hi I am pretty new to C and was wondering how to return an entire array. For example I have this function here.
char* foo(int x)
{
char *num = (char*)malloc(x*sizeof(int));
num[0] = '1';
num[1] = '2';
num[2] = '3';
num[3] = '4';
return num;
}
I realized that when I return num it only returns the first index of num. But is there any way to return the whole array, 1234? Any help will be greatly appreciated!
Since the foo() function returns a pointer, you can see that all values are printed when you use the %s format specifier. The display() function prints the data in the memory area pointed to by the pointer as characters.
#include <stdio.h>
#include <stdlib.h>
char* foo(int x)
{
char* num = (char*) malloc((x + 1) * sizeof(char));
for(size_t i = 0 ; i < x ; ++i)
num[i] = i + 1 + '0';
num[x] = '\0';
return num;
}
void display(char *array, size_t size)
{
for(size_t i = 0 ; i < size && array[i] != '\0' ; ++i)
printf("array[%ld]: %c\n", i, array[i]);
}
int main()
{
const size_t size = 4;
char *result = foo(size);
printf("%s\n", result);
display(result, size);
return 0;
}
Output:
1234
array[0]: 1
array[1]: 2
array[2]: 3
array[3]: 4
See if you are new to C, then learn it first do some googling and research. If you don't find anything then read some theory of a similar topic for examples (How to return an array in C?). After that some error is happening in your code then you can ask it on stackoverflow.
By the way your should be like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *foo(int x); // fix prototype errors
char *foo(int x)
{
char *num = (char *)calloc(x + 1, sizeof(char)); // we added +1 to append the null terminating character in `num`
for (size_t i = 0; i < x; i++)
num[i] = (char)(i + 48);
return num;
}
/* #returns no. of character written on stdout */
int print_foo(const char *num); // fix prototype errors
int print_foo(const char *num)
{
if (num)
{
size_t z = 0;
for (size_t i = 0; i < num[i] != '\0'; i++)
z += fprintf(stdout, "num[%lu] = %c\n", i, num[i]);
return z;
}
return -1;
}
int main(void)
{
char *num = foo(10);
print_foo((const char *)num);
free(num); // free any heap allocated resources before exiting the application
return 0;
}
./a.out "1 23 5 7 2 21"
I want to convert the above string passed as a command line argument into an array of integers in C programming. Would really appreciate help.
Thank you.
A simple loop can solve your problem-
int a[argc];
for(i = 0; i < argc; i++)
{
a[i] = atoi(argv[i+1]);
}
If passing a string
./a.out "1 23 5 7 2 21"
You need to tokenize the string whilst passing the "int" value to an array (which should be dynamic) since you are passing a string and not multiple options. (Which was what I initially thought, but changed)
#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* For strtok */
int main( int argc, char **argv )
{
int i = 0;
int *intArray;
const char s[2] = " ";
char *token;
token = strtok(argv[1], s);
intArray = malloc(sizeof(int));
while( token != NULL )
{
intArray[i++] = atoi(token);
token = strtok(NULL, s);
}
//intArray holds the values but this is to display the results
int j;
for (j=0; j < i ; j++){
printf( " %d\n", intArray[j] );
}
return 0;
}
If passing multiple options (after program name)
./a.out 1 23 5 7 2 21
int i;
int intArray[argc-1];
for (i=0; i < argc - 1; i++){
intArray[i] = atoi(argv[i+1]);
}
return 0;
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, char *argv[]){
if(argc != 2){
exit(EXIT_FAILURE);
}
int n = 0;//number of elements
char prev = ' ', *s = argv[1];
while(*s){
if(isspace(prev) && !isspace(*s))
++n;
prev = *s++;
}
int nums[n];
char *endp;
s = argv[1];
for(int i = 0; i < n; ++i){
nums[i] = strtol(s, &endp, 10);
s = endp;
printf("%d\n", nums[i]);//check print
}
return 0;
}
I want to divide *eString to substrings. Substrings should be like that:
y_{1} = y_{1}y_{m+1}y_{2m+1}...
y_{2} = y_{2}y_{m+2}y_{2m+2}...
y_{m} = y_{m}y_{2m}y_{3m}...
where y is the element of *eString, and y is the substring of these elements.
For instance, if an user expects the key length which is 5, there should be (string size / 5) substrings. y_{1} has to contain the fist element of each divided substring. So, how can I implement this?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ALPHA 26
char *ReadFile(char *);
int main(int argc, char *argv[])
{
double frequency[ALPHA] = {0};
int c = 0;
int keylen = 0;
int counter = 0;
double indexofCoincidence = 0,total = 0;
const char *eString = ReadFile("cipher.txt");
int len = 0;
if (eString) {
puts("The encrypted text is:");
puts(eString);
puts("");
len = strlen(eString);
printf("The length of text is %d\n",len);
}
puts("");
while(eString[c]!= '\0'){
if(eString[c]>= 'a' && eString[c]<='z')
frequency[eString[c]-'a']++;
c++;
}
puts("The letters frequencies are :\n");
for(c=0; c<ALPHA;c++){
if(frequency[c]!= 0)
printf("%c : %.3f\t",c+'a',(frequency[c]/len));
total += (frequency[c]*(frequency[c]-1));
}
indexofCoincidence = (total/((len)*(len-1)));
printf("\n\nIndex of Coincidence : %.3f\n",indexofCoincidence);
if(indexofCoincidence < 0.060){
printf("\nIt looks like randomly.\n");
}
printf("Enter the your expected key length : ");
scanf("%d",keylen);
printf("\n");
char *y;
while(counter != keylen)
{
for(int i = 0; i<(len/keylen);i++){
y[counter] = *eString();
}
counter++
}
return EXIT_SUCCESS;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char *eString = "The quick brown fox jumps over the lazy dog";
int keylen = 5;
int len = strlen(eString);
int y_len = (len + keylen) / keylen + 1;
int i,j;
char **y = malloc(keylen * sizeof(*y));
for(i=0; i < keylen; ++i){
y[i] = malloc(y_len * sizeof(**y));
}
char *p = eString;
i = j = 0;
while(*p){
y[i % keylen][j] = *p++;
y[i % keylen][j+1] = 0;
if(++i % keylen == 0)
++j;
}
//check print & deallocate
for(i = 0; i < keylen; ++i){
printf("y_{%d} : %s\n", i+1, y[i]);
free(y[i]);
}
free(y);
return 0;
}
I need to convert the string "12345678" to the value 00010010001101000101011001111000 (the value in binary only without the zeroes on the left).
So I have written this code in c, the problem is that when I run it does nothing, just waits like there is an error until I stop it manually.
Any ideas?
#include <stdio.h>
#include <string.h>
void reduce(char string[]) {
int i=0, j=0, k=0, cnt=0, tmp=4, num;
char arr[4], result[4*strlen(string)];
for (i=0; i<strlen(string); i++) {
num = atoi(string[i]);
while (num != 0) {
arr[j++] = num%2;
num = num/2;
tmp--;
}
while (tmp != 0) {
arr[j++] = 0;
tmp--;
}
j--;
for (k=i*4; k<(i*4+4); k++) {
result[k++] = arr[j--];
}
j = 0;
tmp = 4;
}
printf("The result is: \n");
for (i=0; i<4*strlen(result); i++) {
printf("%d",result[i]);
}
printf("\n");
}
int main() {
char c[8] = "12345678";
reduce(c);
return 0;
}
Lots of small errors in your code, which makes it hard to pin-point a single error. Main problem seems to be you are confusing binary numbers (0, 1) with ASCII digits ("0", "1") and are mis-using string functions.
as mentioned elsewhere, char c[8] = .. is wrong.
atoi(string[i]) cannot work; it expects a string, not a char. Use `num = string[i]-'0';
arr[..] gets the value 'num%2, that is, a numerical value. Better to use '0'+num%2 so it's a character string.
you increment k in result[k++] inside a loop that already increments k
add result[k] = 0; at the end before printing, so strlen works correctly
4*strlen(result) is way too much -- the strlen is what it is.
you might as well do a simple printf("%s\n", result);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reduce(char string[]) {
int i=0, j=0, k=0, cnt=0, tmp=4, num;
char arr[5], result[4*strlen(string)+1];
for (i=0; i<strlen(string); i++) {
num = string[i]-'0';
while (num != 0) {
arr[j++] = '0'+num%2;
num = num/2;
tmp--;
}
while (tmp != 0) {
arr[j++] = '0';
tmp--;
}
arr[j] = 0;
j--;
for (k=i*4; k<(i*4+4); k++) {
result[k] = arr[j--];
}
j = 0;
tmp = 4;
}
result[k] = 0;
printf("The result is: \n");
for (i=0; i<strlen(result); i++) {
printf("%c",result[i]);
}
printf("\n");
}
int main() {
char c[] = "12345678";
reduce(c);
return 0;
}
.. resulting in
The result is:
00010010001101000101011001111000
It seems from your example that the conversion you are attempting is to binary coded decimal rather than binary. That being the case your solution is somewhat over-complicated; you simply need to convert each digit to its integer value then translate the bit pattern to ASCII 1's and 0's.
#include <stdio.h>
void reduce( const char* c )
{
for( int d = 0; c[d] != 0; d++ )
{
int ci = c[d] - '0' ;
for( unsigned mask = 0x8; mask != 0; mask >>= 1 )
{
putchar( (ci & mask) == 0 ? '0' : '1' ) ;
}
}
}
On the other hand if you did intend a conversion to binary (rather than BCD), then if the entire string is converted to an integer, you can directly translate the bit pattern to ASCII 1's and 0's as follows:
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
void reduce( const char* c )
{
unsigned ci = (unsigned)atoi( c ) ;
static const int BITS = sizeof(ci) * CHAR_BIT ;
for( unsigned mask = 0x01 << (BITS - 1); mask != 0; mask >>= 1 )
{
putchar( (ci & mask) == 0 ? '0' : '1' ) ;
}
}
In your main(), do either
char c[ ] = "12345678";
or
char c[9] = "12345678";
if you want to use c as a string. Otherwise, it does not have enough space to store the terminating null character.
Here, I took the liberty to modify the code accordingly to work for you. Check the below code. Hope it's self-explanatoty.
#include <stdio.h>
#include <string.h>
void reduce(char string[]) {
int i=0, j=0, k=0, cnt=0, count = 0; //count added, tmp removed
char arr[4], result[ (4*strlen(string) )+ 1], c; //1 more byte space to hold null
for (i=0; i<strlen(string); i++) {
c = string[i];
count = 4;
while (count != 0) { //constant iteration 4 times baed on 9 = 1001
arr[j++] = '0' + (c%2); //to store ASCII 0 or 1 [48/ 49]
c = c/2;
count--;
}
/* //not required
while (tmp >= 0) {
arr[j++] = 0;
tmp--;
}
*/
j--;
for (k=(i*4); k<((i*4) +4); k++) {
result[k] = arr[j--];
}
j = 0;
memset (arr, 0, sizeof(arr));
}
result[k] = 0;
printf("The result is: %s\n", result); //why to loop when we've added the terminating null? print directly.
/*
for (i=0; i< strlen(result); i++) {
printf("%c",result[i]);
}
printf("\n");
*/
}
int main() {
char c[ ] = "12345678";
reduce(c);
return 0;
}
Output:
[sourav#broadsword temp]$ ./a.out
The result is: 00010010001101000101011001111000
Convert your string to an integer using int num = atoi(c).
Then do
int binary[50];
int q = num,i=0;
while(q != 0)
{
binary[i++] = q%2;
q = q/2;
}
Printing your binary array is reverse order will have your binary equivalent.
Full program:
#include<stdio.h>
int main(){
char c[100];
int num,q;
int binary[100],i=0,j;
scanf("%d",c);
num = atoi(c);
q = num;
while(q!=0){
binary[i++]= q % 2;
q = q / 2;
}
for(j = i -1 ;j>= 0;j--)
printf("%d",binary[j]);
return 0;
}
You can use the below reduce function.
void reduce(char string[])
{
unsigned int in = atoi(string) ;
int i = 0, result[32],k,j;
while (in > 0) {
j = in % 10;
k = 0;
while (j > 0) {
result[i++] = j % 2;
j = j >> 1;
k++;
}
while (k < 4) {
result[i++] = 0;
k++;
}
in = in/10;
}
printf("Result\n");
for(--i;i >= 0; i--) {
printf("%d", result[i]);
}
printf("\n");
}
For 12345678
the output would be 00010010001101000101011001111000, where each character is printed in its binary format.
It might need some adjustments, but it does the job as it is.
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
int i;
int n;
char *str = "12345678";
const int bit = 1 << (sizeof(n)*8 - 1);
n = atoi(str);
for(i=0; i < sizeof(n)*8 ; i++, n <<= 1)
n&bit ? printf("1") : printf("0");
return 0;
}
This is a very small question, and probably something really silly! But why am I getting garbage returned in my output for this function which should remove double letters?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char *makehello( char *s ) {
char new[16] ;
int i ;
int c = strlen(s);
for ( i = 0; i < (c + 1); i++)
if (toupper(s[i]) != toupper(s[i+1]))
new[i] = toupper(s[i]);
return strdup( new ) ;
}
int main(void) {
char *new;
char data[100];
scanf("%s", data);
new = makehello(data);
printf("%s", new);
return 0;
}
You need a separate count for your 'new' array. You're storing them at index 'i' (where you found the character), but what you really want is to store them from position 0 and increment this count instead.
EDIT: Of course this isn't a fullproof method.
i.e something like this:
for ( i = 0; i < c; i++)
{
if (toupper(s[i]) != toupper(s[i+1]))
{
new[count++]= toupper(s[i]);
}
}
new[count] = '\0';
The line
for ( i = 0; i < (c + 1); i++)
should be
for ( i = 0; i < (c - 1); i++)
And you then need before the strdup new[i]=0;
Braces would not go amise either.
EDIT
Forgot need to change the following
int i, j=0;
and in the for loop
new[j++] = toupper(s[i]);
and after the for loop
new[j] = 0;
Here's a reasonably compact C99 version of the algorithm (headers omitted, example):
const char * makehello (const char * s)
{
char new[16] = { *s, 0 };
const char * p = s;
char c = *s, * q = new;
while (*p) { if (*++p != c) { c = *++q = *p; } }
return strdup(new) ;
}
int main(void)
{
char data[100];
scanf("%s", data);
printf("%s", makehello(data));
return 0;
}
(This one discriminates case.)