c program prints question mark in a box as an output - c

There is a char pointer variable, and its value coming from a function.
char* apple = ....(function call)
I wanted to print this as follows:
int len = strlen(apple);
for(i=0;i<len;i++){
printf("%c ", apple[i]);
}
But in the console, it gives a question mark in a box as an output. What should I do, how should I print it? Thanks.

I dont see issue in the printing part, through the fucntion that retuns pointer to char array needs to be investigatd.
// In this example, getString function returns string literal
// That is being iterated in the next for loop over its length and prints its characters
#include <stdio.h>
#include <stdlib.h>
char *getString(void); // declare
int main() {
char *apple = getString();
int len = strlen(apple);
for(int i = 0; i < len ; i++) {
printf("%c ", apple[i]);
}
return 0;
}
char *getString() {
return "somesthing";
}
Below example will print only printable ascii chars. From 0 to 31 , 0 is for null, 1 is for SOH and so on. Simply you cannot print control codes (ASCII codes < 32) if you print strange output is expected.
#include <stdio.h>
#include <string.h>
#define PRINTABLE_ASCII_CHAR_COUNT 96
/*
Printable chars list
"! " # $ % & ' ( ) * + , - . /
0 1 2 3 4 5 6 7 8 9 : ; < = > ?
# A B C D E F G H I J K L M N O
P Q R S T U V W X Y Z [ \ ] ^ _
` a b c d e f g h i j k l m n o
p q r s t u v w x y z { | } ~"
*/
char *getASCIIs(void);
int main() {
char *apple = getASCIIs();
int len = strlen(apple);
for(int i = 0; i < len ; i++) {
// p << i << ((i % 16 == 15) ? '\n' : ' ');
printf("%c ", apple[i]);
}
return 0;
}
char *getASCIIs() {
static char buffer[PRINTABLE_ASCII_CHAR_COUNT];
for (int i = 32, j=0 ; i <= PRINTABLE_ASCII_CHAR_COUNT; i++, j++) {
buffer[j] = i;
}
return buffer;
}
enter code here

Your syntax seems legit. I highly suspect that cigar[i] donates the proper character that you are looking for. Trying affirming that by casting cigar[i] into a character using (char) cigar[i]. You might output cigar[i] as a string %s as a part of debugging where does it really point at.

Related

Why my number to string converter keeps returning 000?

I have a issue with my number to string implemention. For some reason I keep getting 000 on my terminal even though. I couldn't find a solution, what is the potantial issue here?
Im now sure my code is broken but don't really see the problem.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* public domain code feel free to use as what you wish, no warranties given*/
char finddigits(unsigned n) {
char base = 6;
unsigned tester = 100000;
while(base % tester != 0) {
base--;
/* inefficient but works for now */
switch(tester) {
case 100000:
tester = 10000;
break;
case 10000:
tester = 1000;
break;
case 1000:
tester = 100;
break;
case 100:
tester = 10;
break;
case 10:
tester = 1;
break;
}
}
return base;
}
char* num2str(unsigned n) {
char size = finddigits(n);
char* tempbuf = malloc(size);
*tempbuf = 48 + (n / pow(10, size));
for(unsigned int i = 1; i < size; i++)
*(tempbuf + i) = 48 + (n % (10 * i));
return tempbuf;
}
int main(int argc, char* argv[]) {
int numbr = 210;
printf("%s \n", num2str(numbr));
/* expected 210 on string got 000 */
return 0;
}
You just want num2str to return the digit string for n.
A few issues:
finddigits is supposed to calculate the number of digits in n. But, [if it works at all], it uses an algorithm I've never seen.
finddigits isn't needed in num2str as num2str can be [much] simpler by filling the buffer in the reverse direction.
num2str is too complicated.
Calling num2str from printf leaks memory from the num2str call to malloc
Here's a refactored version:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
char
finddigits(unsigned n)
{
int count = 0;
if (n == 0)
count = 1;
for (; n != 0; n /= 10, ++count);
return count;
}
char *
num2str(unsigned n)
{
static char buf[100];
char *dst = &buf[sizeof(buf) - 1];
// add string terminator
*dst-- = 0;
// we must always output a 0
if (n == 0)
*dst-- = '0';
// work backwards in the array
for (; n != 0; n /= 10, --dst)
*dst = (n % 10) + '0';
// point to first digit in string
dst += 1;
return dst;
}
void
dotest(unsigned n)
{
printf("n=%u '%s'\n",n,num2str(n));
}
int
main(int argc, char *argv[])
{
dotest(210);
dotest(0);
dotest(12345);
return 0;
}
Here's the program output:
n=210 '210'
n=0 '0'
n=12345 '12345'
The computer does what you told it to do, which is to say, it does complete nonsense.
finddigits(210) returns 1, because 6 % 100000 isn't 0 (it's 6), 5%10000 isn't 0 (it's 5), 4 % 1000 isn't 0 (it's 4), 3 % 100 isn't 0 (it's 3), 2 % 10 isn't 0 (it's 2), but 1 % 1 is 0 so the loop stops and the function returns 1.
Then, num2str allocates 1 byte. In this 1 byte, it sets the first byte to 48 + (210 / 10) which is 69, ASCII code for the letter E. Since size is 1 the loop doesn't run at all and num2str returns this allocation. When you print it, it prints the letter E - possibly with more gibberish after it since the string is not terminated, although for me it just printed E.
I have no idea how you managed to get 000.
You need to write code that tells the computer to do what you want it to do. When you can't get it to do what you want it to, for one part of the code, don't just skip that part of the code and go onto the next one. It all has to be right or it won't work.
Mathematics is also "public domain". Here are two versions of one of your functions, shown with a main() that tests both versions with several values.
Don't convert a signed integer value to unsigned for no particular reason. If you need/want the absolute value of a (possibly) negative number, C provides a function to achieve that.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int finddigits1( int n ) {
int count = n == 0; // ensure 0 is counted as 1 digit
while( n ) count++, n /= 10;
return count;
}
int finddigits2( int n ) {
// log of zero is undefined
return ( n == 0 ) ? 1 : (int)log10(abs(n))+1;
}
char *num2str( int n, char buf[] ) {
printf( "finddigits1( %d ) counted %d\n", n, finddigits1( n ) );
printf( "finddigits2( %d ) returns %d\n", n, finddigits2( n ) );
strcpy( buf, "Hello world!" ); // Left as an exercise to fix your own code
return buf; // returning allows direct usage by caller
}
int main() {
int tests[] = { 123, -123, 0, 100, 54321 };
char buf[ 30 ]; // better to pass large buffer to function than use malloc()
for( int i = 0; i < sizeof tests/sizeof tests[0]; i++ ) {
int n = tests[i];
printf( "n = %d '%s'\n", n, num2str( n, buf ) );
}
return 0;
}
finddigits1( 123 ) counted 3
finddigits2( 123 ) returns 3
n = 123 'Hello world!'
finddigits1( -123 ) counted 3 // NB: Account for negative sign!
finddigits2( -123 ) returns 3
n = -123 'Hello world!'
finddigits1( 0 ) counted 1
finddigits2( 0 ) returns 1
n = 0 'Hello world!'
finddigits1( 100 ) counted 3
finddigits2( 100 ) returns 3
n = 100 'Hello world!'
finddigits1( 54321 ) counted 5
finddigits2( 54321 ) returns 5
n = 54321 'Hello world!'
If you're trying to convert a number to a string, why not just use sprintf()?
See here:
How to convert an int to string in C?

How can I code k-map for 4 variable function in C?

I'm trying to create a 4-variable kmap but I am not sure how to create the left side (00->10) of kmap. Thank you for your help. :)
Here is my code
#include <stdio.h>
int main()
{
unsigned int w, x, y, z;
unsigned int f;
/* Print header for K-map. */
printf(" yz \n");
printf(" 00 01 11 10 \n");
printf(" ______________\n");
/* row-printing loop */
for (w = 0; 2 > w; w = w + 1)
{
for (x = 0; 2 > x; x++){
printf("w=%u%x | ", w,x);
}
/* Loop over input variable b in binary order. */
for (y = 0; 2 > y; y = y + 1)
{
/* Loop over d in binary order.*/
for (z = 0; 2 > z; z = z + 1)
{
/* Use variables b and d to calculate *
* input variable c (iterated in *
* Gray code order). */
/* CALCULATE c HERE. */
y = x^z;
/* Calculate and print one K-map entry *
* (function F(a,b,c) ). */
/* INSERT CODE HERE. */
f = (w|~x) & (~w|~y) & (w|~x|~y) & 1;
printf("%u ", f);
}
}
/* End of row reached: print a newline character. */
printf("\n");
}
return 0;
}
For further information, this is what I have to do "Demonstrate its work using f(w,x,y,z) = xy'+w'z and g(w,x,y,z) = w'xyz'+ w + x' as examples"
You have four variables x,y,w,z so you need a kmap with 4x4=16 fields, like the second example in https://www.geeksforgeeks.org/introduction-of-k-map-karnaugh-map/. For the position of the variables and their negations in the kmap replace A,B,C,D with x,y,w,z in the picture :
The translation of letters to binary digits is
Simplify all the terms until no more terms can be simpified, the
output of the example below in this step is: ['10**', '1*0*', '1**0', '*110'] which is same as AB' + AC' + AD' + BCD'
source : https://github.com/zhcHoward/Kmap
So you basically need a square matrix
int matrix[4][4];
/*initialize matrix with '0'*/
for(int i = 0; i < 4; i++)
for(int j = 0; j < 4; j++)
matrix[i][j] = 0;
/* then needed fields to '1' i.e. xy', in most implementations the array is flattened for this */
Source code for a kmap solver is i.e. in http://krunalsiddhapathak.blogspot.com/2013/05/blog-post.html and in https://github.com/Ghost---Shadow/karnaugh-map-simplifier/blob/master/KarnaughMap/Map.cpp
For the verfication step ("Demonstrate that,...") see this .cpp code https://github.com/Ghost---Shadow/karnaugh-map-simplifier/blob/master/KarnaughMap/Simplifier.cpp and for background (POS, SOP, quad, octant,...) https://github.com/tasnim007/K-Map-Solver----Java-Project, https://www.geeksforgeeks.org/introduction-of-k-map-karnaugh-map/ and http://www.nzdl.org/cgi-bin/library?e=d-00000-00---off-0cdl--00-0----0-10-0---0---0direct-10---4-------0-1l--11-en-50---20-about---00-0-1-00-0--4----0-0-11-10-0utfZz-8-00&cl=CL2.4&d=HASHfb0a7f85db79899f86b6a0.8.1.5&gt=1

C - Distinguishing Between Chars and Digits, then Handling Accordingly

I am writing a program that converts user input to either
ASCII values or binary values. If the string contains letters,
each letter should be converted to ASCII. Strings of numbers will
be converted to binary value of entire string. If both letters and
numbers are entered, each letter will be converted to ASCII and the numbers can/will only be separated by letters, for example "32" will print the binary value "00100000", but "3a2" should be converted to "00000011", "97", "00000010".
The way the program is currently written, strings of numbers convert to binary perfectly. However, strings of letters add a decimal "0" to the end. The output converts each letter to its ASCII value, then converts the "0" to binary. I am unsure as to where this "0" is coming from. Additionally, strings beginning
and ending with digits (for example "6j3") will print the ASCII value of j, then the binary value of "6", skipping the "3" entirely and printing the "j" before the "6". I would like to print each ASCII/binary value in the exact order of the user input.
I am posting my entire code for any necessary clarification, but I believe the issue is in the determineChars() function. I am also looking to use the char* letters and char* numbers functions to efficiently handle the appropriate data and store the final num[] and let[] arrays, but I am unsure of how to do this.
I am quite a beginner to C, so excuse the messiness. Corrections, as well as any further optimizations would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <string.h>
#define EIGHT_BITS 255
#define SIXTEEN_BITS 65535
#define THIRTY_TWO_BITS 4294967295UL
#define SIXTY_FOUR_BITS 18446744073709551615ULL
// defined in case of booleans
typedef enum { false, true } bool;
// GET # OF ELEMENTS IN STRING
size_t getSize(char* input) {
size_t size;
size = strlen(input);
printf("Number of Characters..... %d", size);
//printf("\n----------------------------------");
return size;
}
// DETERMINE NUMBER OF BITS TO OUTPUT
int getBitLength(unsigned long long d) {
int l;
if (d <= EIGHT_BITS) {
l = 8;
}
else if (d > EIGHT_BITS && d <= SIXTEEN_BITS) {
l = 16;
}
else if (d > SIXTEEN_BITS && d <= THIRTY_TWO_BITS) {
l = 32;
}
else if (d > THIRTY_TWO_BITS && d <= SIXTY_FOUR_BITS) {
l = 64;
}
printf("\nBits..................... %d", l);
return l;
}
// CONVERT INPUT TO BINARY VALUE
void convertToBinary(char* input) {
static int b[64];
int i, j, length, r;
unsigned long long decimal;
char* pEnd;
// converts input to ull
decimal = strtoull(input, &pEnd, 0);
printf("\n\n---------------- %I64u ------------------", decimal);
printf("\nULL...................... %I64u", decimal);
length = getBitLength(decimal);
// creates array
for (i = 0; i < length; i++) {
r = decimal % 2;
decimal /= 2;
b[i] = r;
}
// reverses array for binary value
printf("\nBinary Value............. ");
for (j = length - 1; j >= 0; j--) {
printf("%d", b[j]);
}
}
char* numbers(char* input) {
char* num = (char*) malloc(sizeof(char) * 25);
return num;
}
char* letters(char* input) {
char* let = (char*) malloc(sizeof(char) * 25);
return let;
}
void determineChars(char* input) {
int i;
char* num = numbers(input);
char* let = letters(input);
size_t inputSize = getSize(input);
// FOR EACH CHARACTER IN INPUT
for (i = 0; i < inputSize; i++) {
if (isdigit(input[i])) {
// stores number values from input into separate array
num[i] = input[i];
printf("\nNumbers: %c", num[i]);
}
if (!isdigit(input[i])) {
// stores letter values from input into separate array
let[i] = input[i];
printf("\nLetters: %c", let[i]);
// prints separator line + ASCII value
printf("\n\n---------------- %c ------------------", let[i]);
printf("\nASCII Value of %c......... %d", let[i], let[i]);
// removes char from input array
input[i] = ' ';
}
}
// char array must consist of digits only
convertToBinary(num);
}
int main() {
// GET INPUT
char input[50];
scanf("%s", input);
determineChars(input);
return 0;
}
I would like to print each ASCII/binary value in the exact order of the user input.
In that case, you would have to restructure your code a bit. This is because if the input contains only digits you will have to print binary and alternate being chars and digits if the string contains both. I have tried to do this with the following code, cleaned it up a bit, removed the warnings and memory leaks.
See if this is what you want:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <string.h>
#define EIGHT_BITS 255
#define SIXTEEN_BITS 65535
#define THIRTY_TWO_BITS 4294967295UL
#define SIXTY_FOUR_BITS 18446744073709551615ULL
// GET # OF ELEMENTS IN STRING
size_t getSize(char* input) {
size_t size;
size = strlen(input);
printf("Number of Characters..... %d\n", size);
//printf("\n----------------------------------");
return size;
}
// DETERMINE NUMBER OF BITS TO OUTPUT
int getBitLength(unsigned long long d) {
int l;
if (d <= EIGHT_BITS) {
l = 8;
}
else if (d > EIGHT_BITS && d <= SIXTEEN_BITS) {
l = 16;
}
else if (d > SIXTEEN_BITS && d <= THIRTY_TWO_BITS) {
l = 32;
}
else if (d > THIRTY_TWO_BITS && d <= SIXTY_FOUR_BITS) {
l = 64;
}
printf("\nBits..................... %d", l);
return l;
}
// CONVERT INPUT TO BINARY VALUE
void convertToBinary(char* input) {
static int b[64];
int i, j, length, r;
unsigned long long decimal;
char* pEnd;
// converts input to ull
decimal = strtoull(input, &pEnd, 0);
printf("\n---------------- %I64u ------------------", decimal);
printf("\nULL...................... %I64u", decimal);
length = getBitLength(decimal);
// creates array
for (i = 0; i < length; i++) {
r = decimal % 2;
decimal /= 2;
b[i] = r;
}
// reverses array for binary value
printf("\nBinary Value............. ");
for (j = length - 1; j >= 0; j--) {
printf("%d", b[j]);
}
printf("\n");
}
void determineChars(char* input) {
int i;
long ret;
char* ptr;
char c;
size_t inputSize = getSize(input);
ret = strtol(input, &ptr, 10);
if((ret == 0) || ((strlen(ptr) != 0) && (strlen(input) != strlen(ptr))))
{
for (i = 0; i < inputSize; i++) {
if (isdigit(input[i])) {
c = input[i];
printf("\nNumber: %c", c);
convertToBinary(&c);
}
if (!isdigit(input[i])) {
// stores letter values from input into separate array
printf("\nLetter: %c", input[i]);
// prints separator line + ASCII value
printf("\n---------------- %c ------------------\n", input[i]);
printf("ASCII Value of %c......... %d\n", input[i], input[i]);
// removes char from input array
}
}
}
else
convertToBinary(input);
}
int main() {
// GET INPUT
char input[50];
scanf("%s", input);
determineChars(input);
}
I also tried out the test cases you mentioned in the question along with few others and it seems to work fine.
32
Number of Characters..... 2
---------------- 32 ------------------
ULL...................... 32
Bits..................... 8
Binary Value............. 00100000
3a2
Number of Characters..... 3
Number: 3
---------------- 3 ------------------
ULL...................... 3
Bits..................... 8
Binary Value............. 00000011
Letter: a
---------------- a ------------------
ASCII Value of a......... 97
Number: 2
---------------- 2 ------------------
ULL...................... 2
Bits..................... 8
Binary Value............. 00000010
6j3
Number of Characters..... 3
Number: 6
---------------- 6 ------------------
ULL...................... 6
Bits..................... 8
Binary Value............. 00000110
Letter: j
---------------- j ------------------
ASCII Value of j......... 106
Number: 3
---------------- 3 ------------------
ULL...................... 3
Bits..................... 8
Binary Value............. 00000011

can anyone help me with this in c?

#include <stdio.h>
#include <conio.h>
#include <string.h>
int main() {
int x,y,z,a;
char arr[221];
char temp;
printf ("Enter values: ");
gets(arr);
a = strlen(arr);
x=a;
while (x!=-1){
printf("\n%s", &arr[x]);
x--;
}
getch ();
}
the output must be like this
sample inputs:
A
2
1
R
X
D
W
note: since A is the first entry to the stack, the stack should look like this:
W D X R 1 2 A
"A" is at the very far end of the array or the stack, it means that "A" is the first one to go out from the stack. Then it is followed by 2, 1, R, and so on...
Your output should look like this:
A
W D X R 1 2
2
W D X R 1
1
W D X R
R
W D X
X
W D
D
W
W
Try this:
x=a-1;
while (x!=-1){
printf("\n%c", &arr[x]);
x--;
}
use x=a-1 and %c instead of x=1 and %s
First of all you are using gets() so the input must follow this format A21RXDW. that is a string. Only in this case the top of stack can have 'A'.
Now
char input[100]={'\0'}; //best practice
scanf("%s",input);
int stack_top = strlen(input) - 1;
//iterate
while(stack_top >= 0){
printf("%c\n", input[stack_top]);
--stack_top;
}

Minesweeper game

do you know the minesweeper game of windows . well , the following problem is the same , you will input m and n ...
0 < n,m <= 100
n : colons , m : rows
input :
4 4
*...
....
.*..
....
output :
*100
2210
1*10
1110
and , that is my code .
#include <stdio.h>
#include <stdlib.h>
char ms[100][101] ;
int m , n;
void input(){
for(int r = 0 ; r < m ; r++)
for(int c = 0 ; c <= n ; c++){
scanf("%c",&ms[r][c]);
if('.' == ms[r][c])
ms[r][c] += 2 ;
}
}
void calc(int m , int n){
for(int r = m ; r <= (m+2) ; r++)
for(int c = n ; c <= (n+2) ; c++)
if(r >= 0 && c >= 0 && ms[r][c] != '*')
ms[r][c] += 1 ;
}
void solve(){
for(int r = 0 ; r < m ; r++)
for(int c = 0 ; c < n ; c++)
if( '*' == ms[r][c])
calc(r-1 , c-1);
}
void output(){
for(int r = 0 ; r < m ; r++)
for(int c = 0 ; c <= n ; c++)
printf("%c ", ms[r][c]);
}
int main()
{
scanf("%d%d" , &m , &n);
input();
solve();
output();
return 0;
}
when running my code , if the input have * at the first as follows :
4 4
*...
....
.*..
....
the output is :
important to see it .. click here
note: i tried to print the value of the symbol that appeard in the picture and it is 11 in ascii code which is vertical tab.
and , another problem if the * is at the last as follows :
4 4
...*
....
....
...*
000*
0000
0000
000*
but my code works well when the * is at the middle as follows :
4 4
....
..*.
.*..
....
0111
12*1
1*21
1110
so , what's the problem with my code ?
In this line you can go out of bounds:
if(r >= 0 && c >= 0 && ms[r][c] != '*')
ms[r][c] += 1 ;
You only test if r and c are not negative, but you should also test they are not too large.
The thing becomes more complicated because you have global variables m and n which are the dimensions of your array, but they are not available in the calc function, because there you have local variables with the same name.
So you better use different variable names. And then you should test that r<m and c<n, as follows:
void calc(int p , int q){
for(int r = p ; r <= (p+2) ; r++)
for(int c = q ; c <= (q+2) ; c++)
if(r >= 0 && c >= 0 && r < m && c < n && ms[r][c] != '*')
ms[r][c] += 1 ;
}
Now the reason you saw an ASCII 11 is explained by the fact that ASCII 10 is the line feed character that marks the end of a row. Then when your code performs ms[r][c] += 1 on it (because it goes too far), it becomes that funny character.
That you have that ASCII 10 in your array is explained by how you read the input (see #pmg's answer). If you would not have read those white space characters, you would still overrun, and probably touch data in a next row of data, which is not what you want to happen.
scanf("%d", ...);
leaves whitespace (the ENTER) in the input buffer. Then
scanf("%c", ...);
reads that whitespace into the variable.
You need to ignore the whitespace before (and during) reading the stars and dots.
Use
scanf(" %c", ...);
// ^^^ ignore whitespace
Note: the conversion specifier "%d" (and many others) already includes ignoring whitespace; the exceptions are "%c", "%[", and [for different reasons] "%n").

Resources