C - Loop ends unexpectedly - c

So I am trying to make a infix to postfix program in C but when I start entering the symbols, the loop ends at the first entry.
I am pretty sure it's a data type problem somewhere but I can't figure out where..
Here is the code:
#include <stdio.h>
#include <stdlib.h>
static int N;
static char *s;
void stackinit(int max){
s = malloc(max*sizeof(int));
N = 0;
}
int stackempty(){
if(N==0)
return(1);
else
return(0);
}
void stackpush(char item){
s[N] += item;
N++;
}
int stackpop(){
N--;
return(s[N]);
}
int priority(char x){
if(x == '+' || x == '-')
return(0);
if(x == '*' || x == '/')
return(1);
}
int main(void){
int i,sum;
char input;
printf("Infix to Postfix\n");
printf("How many characters will you enter?");
scanf("%d", &sum);
stackinit(sum);
for(i = 0; i < sum; i++){
printf("Enter character: ");
scanf("%s", &input);
stackpush(input);
}
while(!stackempty()){
printf("%d ", stackpop());
}
/*for(i = 0; i < sum; i++){
}*/
}

scanf() uses %c to reading characters, so your code should be
scanf(" %c", &input);
By adding a space after your %c specifier, you also consume any new line or space characters that might be added unintendedly, then correcting your loop issue.
As another thought, you will need to append an extra character onto your string: a null character, which is a '\0' character. This is why you will need to do s = malloc(max*sizeof(int) + 1);, so that you have space left for your '\0', which, in your case, you can add dynamically on your stackPush() function, like that:
void stackpush(char item){
s[N++] = item;
s[N] = '\0';
}
Also, in your stackPush function, what you want is s[N] = item;, not s[N] += item;
More on C Strings

Related

How can I pass a stdin as an argument for my function?

My first program. I would like it if the user enters a word made of letters and then it uses my loop function to output mixed up even and odd characters. Currently I cannot get it to compile. Bonus points if someone can show me how to loop the users input so after it asks the size to make the array, it prompts the user that many times for an "element" or word so that the function can scramble it and output it.
#include <stdio.h>
char transform(char str[]);
int main()
{ //Declare an array and size variable
int size = 0;
char str[size];
printf("How many elements?");
scanf("%d", &size);
printf("Please type an element: ");
//Get input from user
str[0] = scanf("%s", str);
transform(str);
printf("Please type another element: ");
//Get another input from user
str[1] = scanf("%s", str);
transform(str);
//This is the loop function that I programmed
char transform(char str[]);
{
//Loop that prints even characters
for (int i = 0; str[i] != '\0'; i++)
{
if(i % 2 == 0)
{
printf("%c", str[i]);
}
} //Space between even/odd characters
printf(" ");
//Loop that prints odd characters
for (int i = 0; str[i] != '\0'; i++)
{
if(i % 2 != 0)
{
printf("%c", str[i]);
}
}
printf("\n");
return 0;
}
}
#include <stdlib.h>
#include <stdio.h>
char transform(char str[]);
int main()
{ //Declare an array and size variable
int size = 0;
printf("How many elements?");
scanf("%d", &size);
for (int i = 0; i < size; ++i)
{
printf("Please type an element: ");
char str[2048]; //declare a wide buffer to be able to store lots of chars
scanf("%s", str);
transform(str);
}
return 0;
} //end your main here, by putting closing brace
char transform(char str[]) //define transform without semicolon, and outside of main
{ //This is the loop function that I programmed
//Loop that prints even characters
for (int i = 0; str[i] != '\0'; i++)
{
if (i % 2 == 0)
printf("%c", str[i]);
} //Space between even/odd characters
printf(" ");
//Loop that prints odd characters
for (int i = 0; str[i] != '\0'; i++)
{
if (i % 2 != 0)
printf("%c", str[i]);
}
printf("\n");
return 0;
}

recursive count number in c using function

I try to make a recursive program but it's doesn't work.
the program to count number in teks.
example :
input:
abcde1234
and
output :
4
this my code :
#include<stdio.h>
int count_digits(char s[]);
int main (){
char x[1000];
printf("input string (max 1000 character): ");
scanf("%s", &x);
printf("number of digits in the text = %i", count_digits(x));
return 0;
}
int count_digits(char s[]){
int j, digits=0;
for (j=0; s[j] !='0'; j++)
{
if(s[j] >= '0' && s[j] <= '9'
{
digits++;
}
}
}
maybe anyone can help me to fixed it :) . my program still show output = 9 not 4.
You have to return the calculated value. Add in the end of your function:
return digits;
By the way, you program in not written in recursive approach.
should be something like:
int count_digits(char s[]){
if (!*s)
return 0;
return (*s >= '0' && *s <= '9') + count_digits(s+1);
}
scanf("%s", &x); invokes undefined behavior by passing data having wrong type. The & should be removed.
The loop condition s[j] !='0' is wrong. It should be s[j] !='\0' to stop at the terminating null-character.
You forgot to add ) at the end of if line.
You forgot to return the result digits from the function count_digits.
Try this:
#include<stdio.h>
int count_digits(char s[]);
int main (){
char x[1000];
printf("input string (max 1000 character): ");
scanf("%s", x); /* remove extra & */
printf("number of digits in the text = %i", count_digits(x));
return 0;
}
int count_digits(char s[]){
int j, digits=0;
for (j=0; s[j] !='\0'; j++)
{
if(s[j] >= '0' && s[j] <= '9') /* add ) */
{
digits++;
}
}
return digits; /* return the result */
}
Then, try to make the recursive version!

How can I take input character in a character array using %c and produce the right output using %s?

This is my code.
#include<stdio.h>
#include<string.h>
int main()
{
int n, i;
char ch[100];
scanf("%d", &n);
for(i = 0; i < n; i++){
scanf(" %c", &ch[i]);
}
printf("%s\n", strupr(ch));
return 0;
}
At first, I want to take the size of the character array in n variable. After, i want to take n character's and assign the array. The output comes from this program is right but it also produce some garbage values.
For example:
5
s d g h f
Output: SDGHFC└U▄■`
How can i ignore the garbage values from my output?
Simply initialize your array ch[] to all zeros. I.E.
for (i = 0; i < 100; i += 1) { ch[i] = '\0'; }
Put this line just after the declaration of ch[].
As you are reading character the spaces you are providing in your input, will also be considered as characters, and strupr(c) will give some shaggy output, also you have to manually provided null character at the end of your character array. Below program might help you find your answer
#include<stdio.h>
#include<string.h>
int main()
{
int n, i;
scanf("%d", &n);
fflush(stdin);
char ch[100];
for(i = 0; i < n; i++){
char temp;
scanf("%c", &temp);
if(temp != '\n')
ch[i] = temp;
else
break;
}
ch[n] = '\0';
printf("%s\n", strupr(ch));
return 0;
}
Your Input should look like
5
sdghf
To give input with spaces. Program will look like.
#include<stdio.h>
#include<string.h>
int main()
{
int n, i;
scanf("%d", &n);
fflush(stdin);
char ch[100];
char temp;
i = 0;
while(scanf("%c", &temp)){
if(temp == ' ')
continue;
if(temp != '\n')
ch[i++] = temp;
else
break;
}
ch[i] = '\0';
printf("%s\n", strupr(ch));
return 0;
}
Now, you can give your character in any arrangement as you want.

C: Format specifies type 'char *'

Whenever I run the following code, I get the error message
"format specifies type char * but the argument has type int."
The program is supposed to print a n by n square or triangle of a specific character. I'm pretty new to C, and I haven't had much luck troubleshooting this.
#include <stdio.h>
#include <ctype.h>
void print_square(int n, char c) {
for (int i=0; i < n; i++) {
for (int j; j < n; j++) {
printf("%c", c);
}
printf("\n");
}
}
void print_triangle(int n, char c) {
int count = 1;
for (int i=0; i < n; i++) {
for (int j; j < count; j++) {
printf("%c", c);
}
count = count + 1;
printf("\n");
}
}
int main(int argc, const char * argv[]) {
int n;
char cmd;
char * c;
do {
printf("Enter T for a triangle, S for a square, "
"Q to quit: ");
scanf("%c", &cmd);
cmd = toupper(cmd);
if (cmd == 'S' || cmd == 'T') {
printf("Enter the size: ");
scanf("%d", &n);
printf("Enter the character: ");
scanf("%c", *c); // error here
if (cmd == 'S') {
print_square(n, *c);
}
else {
print_triangle(n, *c);
}
}
} while (cmd != 'T' && cmd != 'S' && cmd != 'Q');
return 0;
}
As you've pointed already, the error is indeed in
scanf("%c", *c);
You need to pass a valid pointer to char, why to dereference?
Note: In your case, you're dereferencing an unitialized pointer, which invokes undefined behavior, anyway.
To have a better approach (you dont really need c to be a pointer there) do something like
char c;
scanf(" %c", &c); //the leading space consumes the newline in input bufer
and you should be good to go.
Accordingly, you need to pass c instead of *c, as required in other function calls.

int array doesnt get char values

I am absolutely brand new at programming and im not sure how to explain what im doing here.
The whole purpose of this piece is to enter values and then print them out in the same order. Now I wanna quit from entering values when pressing 'q' and so I have to scanf for chars but when I assign them back to the int array the values are not the same.
Hope that makes any sense to you but in any case heres my code:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5000
define flush fflush(stdin)
main() {
int input[SIZE] = {0},i = 0;
int counter = 0;
char inputs, quit;
do {
system("cls");
printf("Input number ('q' to quit and display numbers entered): ");
flush;
scanf("%c",&inputs);
flush;
if (inputs == 'q')
quit = 'q';
else {
input[i] = inputs;
counter++;
i++;
}
} while (i < SIZE && quit != 'q');
for(i = 0; i < counter; i++){
printf("%i.%i\n", i + 1, input[i]);
}
system("pause");
}
Ive been trying to do this on my own btw and also researched some information online regarding chars but couldnt find anything that would help me. Thanks a lot in advance.
You should nor be getting integer through %c neither assign char values to integers variables when that is not the intention, rather you should approach something like this
i = 0;
do {
printf("Enter a number: ");
scanf("%d", &input[i]);
i++; counter++;
printf("Do you want to continue? (y/n) : ");
scanf("%c", &inputs);
} while(inputs == 'y');
or u can get the number of integer inputs upfront and loop to get that much integers.
try instead (using your original code as much as possible):
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define SIZE 5000
int main()
{
int input[SIZE] = {0},i = 0;
int counter = 0;
char inputs[32];
bool quite = false;
do
{
system("cls");
printf("Input number ('q' to quit and display numbers entered): ");
// read a string from user, then convert when appropr
fgets(stdin, sizeof(inputs), inputs);
if (inputs[0] == 'q')
{
quit = true;
}
else if ( isdigit(inputs[0]) )
{
input[i] = atoi(inputs); // this will disregard any ending \n
counter++;
i++;
}
}
while (i < SIZE && !quit);
for(i = 0; i < counter; i++)
{
printf("%i.%i\n", i + 1, input[i]);
}
system("pause");
}
Another variant. This one will read in characters regardless of the use of whitespaces, since it uses getchar() rather than scanf(). I'm not sure if this is what you want. It seems as though you want integers but are reading characters. So this solution may be completely off base.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5000
int main()
{
char input[SIZE] = {0};
int i = 0;
int counter = 0;
char inputs;
printf("Input number ('q' to quit and display numbers entered): ");
while (((inputs = getchar()) != EOF) && (counter < SIZE))
{
if (inputs == 'q')
break;
input[counter] = inputs;
counter++;
}
for(i = 0; i < counter; i++)
{
printf("%c\n", input[i]);
}
system("pause");
return 0;
}
If you do really want ints, this one should work.
Notice that the atoi() function can be used to convert a C-string to an int.
The fgets() function is used to read the C-string from STDIN. However, scanf("%s", input); would also work here, as opposed to the scanf("%c", &inputs); that you used.
#include <stdio.h>
#include <stdlib.h>
#define INPUT_SIZE 1000
#define SIZE 5000
int main()
{
char input[INPUT_SIZE] = {0};
int numbers[SIZE] = {0};
int i = 0;
int counter = 0;
while ((fgets(input, sizeof(input), stdin) != NULL) && (counter < SIZE))
{
system("cls");
printf("Input number ('q' to quit and display numbers entered): ");
if (input[0] == 'q')
break;
numbers[counter] = atoi(input);
counter++;
}
for(i = 0; i < counter; i++)
{
printf("%i\n", numbers[i]);
}
system("pause");
return 0;
}

Resources