I tried to create an own printf function only for printing double, int and character value, here goes the code
#include<stdarg.h>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
void inta(int ch) {
int count = 0;
int num = ch;
while (ch != 0) {
ch /= 10;
count++;
}
int t = 0;
char *s = (char*) calloc((count + 1), (sizeof(char)));
printf("%s\n", s);
while (num > 0) {
s[t] = 48 + (num % 10);
num /= 10;
t++;
}
s[t] = '\0';
int len = t - 1;
for (int a = 0; a < t / 2; a++) {
char temp = s[a];
s[a] = s[len];
s[len] = temp;
len--;
}
for (int a = 0; a < t; a++) {
putch(s[a]);
}
}
void floata(double num) {
int n = (int) num;
inta(n);
double rem = num - n;
//printf("rem = %lf\n",rem);
while (1) {
if (rem - (int) rem < 0.0001) {
break;
} else {
rem *= 10;
// printf("rem npw %lf\n",rem);
}
}
putch('.');
inta(rem);
}
void chara(int ch) {
putch(ch);
}
void print(const char *str, ...) {
float p;
int ch;
va_list ap;
va_start(ap, str);
char *fmt;
for (fmt = str; *fmt != '\0'; fmt++) {
while (*fmt != '%') {
putch(*fmt);
fmt++;
}
fmt++;
switch (*fmt) {
case 'c':
ch = va_arg(ap, int);
chara(ch);
break;
case 'd':
ch = va_arg(ap, int);
if (ch < 0) {
putch('-');
ch = -ch;
}
inta(ch);
break;
case 'f':
p = va_arg(ap, double);
if (p < 0) {
putch('-');
p = -p;
}
floata(p);
break;
}
}
va_end(ap);
}
int main() {
int q = 119;
double aa = 12.34;
int a = 123;
char b = 'z';
print("%d %f %c", q, aa, b);
}
The expected output should be:
123 12.34 z
but the output is:
119
12.
34 z
I used putch function to print every character, why some newlines is being created?
How to remove this newline>?
How to remove this newline>?
Remove printf("%s\n", s);
Related
I'm trying to count chars from input, and I noticed that while(getchar()!=EOF) produces an extra count, Is it because it counts the null-terminated from input?
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define LINE 5
#define MEM_SIZE 10
char *getInput(int *counter);
void printInput(char *input);
int main() {
char *mainInput;
int counter = 0;
printf("Please enter your input:\n");
mainInput = getInput(&counter);
if (mainInput == NULL) {
return 1;
}
printf("\n\n\nOutput:\n%s\n", mainInput);
printf("number of chars: %d\n", counter);
printInput(mainInput);
free(mainInput);
return 0;
}
char *getInput(int *counter) {
char *p = (char *)malloc(MEM_SIZE * sizeof(char));
char *q = p; /* backup pointer, if realloc fails to allocate, function will return last address values stored */
int c;
int temp_counter = 0;
long current = 0, last = MEM_SIZE - 1;
while ((c = getchar()) != EOF) {
if (current >= last) {
q = p;
p = (char *)realloc(q, last + (MEM_SIZE * sizeof(char)));
if (p == NULL) {
printf("Memory allocation failed, printing only stored values \n");
return q;
}
last += MEM_SIZE;
}
p[current] = c;
temp_counter++;
printf("number of chars: %d\n", temp_counter);
++current;
}
p[current] = '\0';
(*counter) = temp_counter - 1;
return p;
}
void printInput(char *input) {
int i, j = 0;
while (input[j] != '\0') {
for (i = 0; i < LINE; i++) {
if (input[j] == '\0')
break;
putchar(input[j]);
++j;
}
if (input[j] != '\0')
putchar('\n');
}
}
# include <stdio.h>
int main(){
int a,b;
scanf("%d %d",&a,&b);
while (a > 0) {
int digit = a % 10;
//printf("%d ",digit); for testing
a = a - digit;
a /= 10;
}
while (b > 0) {
int digit = b % 10;
//printf("%d ",digit); for testing
b = b - digit;
b /= 10;
}
}
This code takes two integers with the same lengths(a,b), splits them into their characters, now the question is how to print it like this for example(a=123 , b= 798 --> result = 17-29-38
Save the digits in arrays. Then you can loop over the arrays to print the digits at the end.
Also, you don't need to subtract digit before dividing by 10, since division discards the remainder.
# include <stdio.h>
#define MAXDIGITS 20
int main(){
int a,b;
int adigits[MAXDIGITS], bdigits[MAXDIGITS];
int digits = 0;
scanf("%d %d",&a,&b);
while (a > 0) {
int digit = a % 10;
//printf("%d ",digit); for testing
adigits[digits++] = digit;
a /= 10;
}
digits = 0;
while (b > 0) {
int digit = b % 10;
//printf("%d ",digit); for testing
bdigits[digits++] = digit;
b /= 10;
}
while (--digits >= 0) {
printf("%d%d", adigits[digits], bdigits[digits]);
if (digits != 0) {
putchar('-');
}
}
putchar('\n');
}
Your input is strings, and there is no point in converting those strings to integers just to change them back. Just work on the data directly. eg:
#include <stdio.h>
#include <stddef.h>
#include <ctype.h>
#include <stdlib.h>
struct buffer {
char *start;
char *end;
size_t cap;
};
void push(int c, struct buffer *);
int pop(struct buffer *);
void * xrealloc(void *buf, size_t num, size_t siz, void *offsetp);
int
main(void)
{
struct buffer a = {0};
struct buffer b = {0};
int c;
while( (c = getchar()) != EOF && !isspace(c) ) {
push(c, &a);
}
while(isspace(c = getchar())) {
;
}
ungetc(c, stdin);
while( (c = getchar()) != EOF ) {
push(c, &b);
}
while( (c = pop(&a)) != EOF ) {
putchar(c);
if( (c = pop(&b)) != EOF ) {
putchar(c);
}
}
while( (c = pop(&b)) != EOF ) {
putchar(c);
}
return 0;
}
int
pop(struct buffer *a)
{
return (a->start < a->end) ? *a->start++ : EOF;
}
void
push(int c, struct buffer *b)
{
if( b->start == NULL ) {
b->end = b->start = xrealloc(NULL, b->cap = 8, 1, NULL);
} else if( b->end >= b->start + b->cap ) {
b->start = xrealloc(b->start, b->cap *= 2, 1, &b->end);
}
*b->end++ = c;
}
void *
xrealloc(void *buf, size_t num, size_t siz, void *offsetp)
{
ptrdiff_t offset;
void **iterator = offsetp;
if( iterator != NULL ) {
offset = *iterator - buf;
}
buf = realloc(buf, num * siz);
if( buf == NULL ) {
perror("realloc");
exit(EXIT_FAILURE);
}
if( iterator != NULL ) {
*iterator = buf + offset;
}
return buf;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Stack
{
char stk[50][50];
int top;
};
typedef struct Stack stack;
void push(stack *p, char c)
{
p->top++;
p->stk[p->top][0] = c ;
p->stk[p->top][1] = '\0';
}
void puush(stack *p, char val[])
{
p->top++;
int i=0 , len = strlen(val);
for( i = 0; i< len ; i++)
p->stk[p->top][i] = val[i];
p->stk[p->top][i] = '\0';
}
void pop(stack *p)
{
p->top--;
}
char *top(stack *p)
{
return p->stk[p->top];
}
void print(stack *p)
{
int i = 0;
while(i <= p->top)
{
printf("index : %d elements : %s\n", i+1, p->stk[i]);
i++;
}
printf("\n");
}
int isOperand(char c)
{
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
return 1;
else return 0;
}
int isOperator(char c)
{
switch(c)
{
case '+':
case '-':
case '*':
case '/':
return 1;
default:
return 0;
}
}
void prefixToInfix(char s[])
{
stack s1;
s1.top = -1;
int i=0, len = strlen(s) - 1;
for(i = len ; i>= 0 ; i--)
{
if(isOperand(s[i]))
{
printf("%c\n\n",s[i]);
push(&s1, s[i]);
print(&s1);
}
if(isOperator(s[i]))
{
char concat[20];
int k,j= -1;
concat[++j] = '(';
char *c1 = top(&s1);
pop(&s1);
int len1 = 0;
len1 = strlen(c1);
for(k=0; k<len1; k++)
{
concat[++j] = c1[k];
}
concat[++j] = s[i];
c1 = top(&s1);
len1 = strlen(c1);
pop(&s1);
for(k= 0; k<len1; k++)
concat[++j] = c1[k];
concat[++j]=')';
concat[++j] = '\0';
printf("gnerated %s\n",concat);
puush(&s1, concat);
print(&s1);
}
}
printf("%s",top(&s1));
}
int main()
{
prefixToInfix("*-A/BC-/AKL");
}
Please help me, I am not getting the correct output as it should be. I am sharing my code thus it will be easier for you all to understand the problem of my Code
Explanation of my problem:
I have been trying to write a code which converts The Prefix form to Infix. I am getting the output as I expected except one extra parenthesis at last:
For example:
The Input: "*-A/BC-/AKL"
Expected Output: ((A-(B/C))*((A/K)-L)
However my Program output:
((A-(B/C))*((A/K)-L)(, the last extra parenthesis is the issue "("
My rpn-calculator works, but it has a problem. The problem is that it prints out every consecutive calculation that it makes along the way.
I have tried different ways of fixing this, the latest one being adding an integer that goes up by every calculation and a printf that prints if this integer is above 0 as well as there only being one number on the stack.
However, this causes problems when there is more than one calculation going on (for example writing 5 5 + 10 5 * *) will cause 10 500 being printed out because there is only one item on the stack after the first calculation.
How can I solve this?
#define MAX_STACK_SIZE 100
#define MAX_BUFFER_SIZE 100
char buff[MAX_BUFFER_SIZE];
double x, stack[MAX_STACK_SIZE];
double t;
int i, k=0, num_operand=0;
int main(void) {
while(x != 'q') {
if( scanf("%s", buff) < 1 )
{ return 0;
}
if(isdigit(buff[0]) || isdigit(buff[1])) {
sscanf(buff, "%lf", &x);
if (num_operand < MAX_STACK_SIZE)
{
stack[num_operand]=x;
num_operand ++;
} else { printf("Make stack bigger\n");}
} else {
switch(buff[0]) {
case '+': stack[num_operand - 2] = stack[num_operand - 1] + stack[num_operand - 2];
num_operand --;
num_operand --;
t = stack[num_operand];
k++;
num_operand ++;
break;
case '-': stack[num_operand - 2] = stack[num_operand - 2] - stack[num_operand - 1];
num_operand --;
num_operand --;
t = stack[num_operand];
k++;
num_operand ++;
break;
case '/': stack[num_operand - 2] = stack[num_operand - 2] / stack[num_operand - 1];
num_operand --;
num_operand --;
t = stack[num_operand];
k++;
num_operand ++;
break;
case '*': stack[num_operand - 2] = stack[num_operand - 1] * stack[num_operand - 2];
num_operand --;
num_operand --;
t = stack[num_operand];
k++;
num_operand ++;
break;
} }
if (num_operand == 1 && k !=0) {
k = 0;
printf("%lf \n", t); }
}
}
"%s" consumes leading white-spaces like ' ' and '\n' alike - so the distinction between end of line and the space separator is lost.
To distinguish between lines of input use fgets() and process the line. Then print the result. #molbdnilo
It test for q, code needs to test the textual contents of the line, not double x. #BLUEPIXY
int main(void) {
char line[MAX_BUFFER_SIZE];
// read line
while (fgets(line, sizeof line, stdin) && line[0] != 'q') {
// Set up these variables per each line.
double x, stack[MAX_STACK_SIZE];
double t;
int i, k = 0, num_operand = 0;
const char *p = line;
char buff[MAX_BUFFER_SIZE];
int n; // # of characters scanned
// process tokens
while (sscanf(p, "%s %n", buff, &n) == 1) {
...
// next token
p += n;
} // endwhile
// print
if (num_operand == 1 && k != 0) {
k = 0;
printf("%lf \n", t);
fflush(stdout);
}
} // endwhile
Instead of displaying by the number of stacked on the stack, make sure to display the stack top explicitly with the command.
Specific example.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#include <ctype.h>
#define MAX_STACK_SIZE 100
#define MAX_BUFFER_SIZE 100
char buff[MAX_BUFFER_SIZE];
char *curr_buff = buff;
double stack[MAX_STACK_SIZE];
int sp = -1;
#define prompt " ok>"
char *getToken(void);
bool IsNumber(const char *token, double *value);
char *strlwr(char *s);
int cmp_charpp(const void *, const void *);
void push(double value);
double pop(void);
void add(void);
void sub(void);
void mul(void);
void Div(void);
void dot(void);
void Exit(void);
void quit(void);
void bye(void);
void cr(void);
struct command {
const char *name;
void (*func)(void);
} op_table[] = {
{"*" , mul},
{"+" , add},
{"-" , sub},
{"." , dot},
{"/" , Div},
{"=" , dot},
{"add" , add},
{"bye" , bye},
{"cr" , cr},
{"div" , Div},
{"exit", Exit},
{"mul" , mul},
{"quit", quit},
{"sub" , sub},
};
int main(void) {
while(true){
char *token;
fputs(prompt, stdout);fflush(stdout);
while(token = getToken()){
double value = 0;
if(IsNumber(token, &value)){
push(value);
} else if(*token){
strlwr(token);
struct command *op =
bsearch(&token, op_table,
sizeof(op_table)/sizeof(*op_table), sizeof(*op_table),
cmp_charpp);
if(op){
op->func();
} else {
fprintf(stderr, "\ncommand '%s' not found!!\n", token);
curr_buff = buff;
*buff = 0;
break;
}
}
}
}
}
char *getToken(void){
static char token[MAX_BUFFER_SIZE] = "";
if(curr_buff){
if(*curr_buff || curr_buff == buff && (curr_buff = fgets(buff, sizeof buff, stdin))){
int n = 0;
if(sscanf(curr_buff, "%s %n", token, &n) == 1){
curr_buff += n;
return token;
}
}
*(curr_buff = buff) = 0;
}
return NULL;
}
bool IsNumber(const char *token, double *value){
char ch = 0;
*value = FP_NAN;
return sscanf(token, "%lf%c", value, &ch)==1;
}
void push(double value){
if(sp+1 == MAX_STACK_SIZE){
fprintf(stderr, "\nstack overflow!!\n");
return;
}
stack[++sp] = value;
}
bool IsEmpty(void){
return sp == -1;
}
double pop(void){
if(IsEmpty()){
fprintf(stderr, "\nstack is empty!!\n");
return nan(NULL);//FP_NAN;
}
return stack[sp--];
}
bool pop2(double *top, double *second){
return !isnan(*top = pop()) && !isnan(*second = pop());
}
void add(void){
double top, second;
if(pop2(&top, &second))
push(second+top);
}
void sub(void){
double top, second;
if(pop2(&top, &second))
push(second-top);
}
void mul(void){
double top, second;
if(pop2(&top, &second))
push(second*top);
}
void Div(void){
double top, second;
if(pop2(&top, &second))
push(second/top);
}
void dot(void){
double top = pop();
if(!isnan(top)){
printf("%g", top);fflush(stdout);
}
}
void cr(void){
putchar('\n');
}
void Exit(void){
double top = pop();
if(isnan(top))
exit(EXIT_FAILURE);
else
exit((int)top);
}
void quit(void){
char yn[4];
if(!IsEmpty()){
printf("The stack is not empty but will it end?\n");
scanf(" %3[NYny]", yn);
if(*yn == 'y' || *yn == 'Y')
exit(EXIT_SUCCESS);
else
while(getchar()!='\n');
}else {
exit(EXIT_SUCCESS);
}
}
void bye(void){
exit(EXIT_SUCCESS);
}
char *strlwr(char *s){
for(char *p = s; *p; ++p)
*p = tolower(*p);
return s;
}
int cmp_charpp(const void *a, const void *b){
return strcmp(*(const char **)a, *(const char **)b);
}
Example of execution.
ok>5 5 + 10 5 * * = CR
500
ok>bye
I was assigned with a task of completing an assignment in C, without being taught C. (I have been learning Java) I am not sure how to fix this error nor do I know what the error means.
#include <stdio.h>
//int mystrcmp(char * s, char * t);
int main(int argc, char * argv[])
{
// #1 Prints out cmd line arguments
int i;
for (i = 0; i < argc; ++i)
{
printf("%s\n",argv[i]);
}
printf("\n"); //Spaceholder
// #2 String Compare
printf("%s %s\n", argv[1], argv[2]);
printf("Returned Value: %d\n", mystrcmp(argv[1], argv[2]));
//mystrcmp(argv[1],argv[2]);
// #3 String Concatenate
printf("\n"); //Spaceholder
printf("String Concatenate: %s\n", mystrcat(argv[1]));
// #4 String Copy
printf("\n"); //Spaceholder
// printf("String Copy: %s\n" , mystrcpy(argv[1]));
}
///////////
//Methods//
///////////
/* srtcmp: return < 0 if s < t, 0 if s==t, > 0 if s > t */
int mystrcmp(char * s, char * t)
{
int i;
for(i = 0; s[i] && s[2]; ++i)
{
if (s[i] == t[i] || (s[i]) == t[i])
continue;
else
break;
}
if (s[i] == t[i])
return 0;
if ((s[i]) < (t[i]))
return -1;
return 1;
}
mystrcat(char *dest, char *source)
{
int a = 0;
while(*(dest + a) != '\0')
{
a++;
}
int b = 0;
while(*(source + a) != '\0')
{
*(dest + a) = *(source + b);
a++;
b++;
}
}
mystrcpy(char * s, char * dest)
{
while((*s++ = *dest++)!= '\0')
;
return *dest;
}
I am assuming the error is coming from my mystrcat.
while(*(source + a) != '\0')
should be
while(*(source + b) != '\0')