C: Format specifies type 'char *' - c

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.

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;
}

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.

In this program, why does getchar() end my loop [duplicate]

This question already has answers here:
Difference between scanf("%c", &c) and scanf(" %c", &c) [duplicate]
(3 answers)
Reading a character with scanf_s
(3 answers)
Closed 4 years ago.
In the main function if i simply declare the replacement character like this..
c = '*';
the program will keep looping normal and work normal after user enters y or Y to proceed.
But if i want the user to enter the replacement character and do this..
c = getchar();
after the user enters either y or Y, the loop ends and the program just closes.
Why is this?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define BUFF_SIZE 512
void getRandomStr(char s1[]);
void strreplace(char s1[], char chrs[], char c);
void check(char s2[], char chrs[]);
char cont(void);
int main()
{
char s1[BUFF_SIZE];
char s2[BUFF_SIZE], c;
char proceed = 0;
do {
getRandomStr(s1);
printf("Your random string is: %s\n", s1);
/* gets(s1) */
printf("\nPlease enter up to 20 letters to be replaced: ");
gets(s2);
printf("\nPlease enter a replacement character (Ex. *, $, etc.): ");
c = getchar();
check(s1, s2);
printf("\nModified string after replacement is: ");
strreplace(s1, s2, c);
proceed = cont();
} while (proceed == 'Y' || proceed == 'y');
}
void getRandomStr(char s1[]) {
int i;
srand(time(NULL));
for (i = 0; i < 41; i++) {
char c = rand() % 26 + 'A';
s1[i] = c;
}
s1[41] = '\0';
}
void strreplace(char s1[], char chrs[], char c)
{
int i = 0;
while (chrs[i] != '\0') {
for (int j = 0; s1[j] != '\0'; j++) {
if (s1[j] == chrs[i])
{
s1[j] = c;
}
}
i++;
}
puts(s1);
}
char cont()
{
char proceed;
printf("\nWould you like to run the program again (y/n)? ");
scanf_s("%c%*c", &proceed);
return proceed;
}
void check(char s2[], char chrs[])
{
int i = 0;
while (chrs[i] != '\0') {
for (int j = 0; s2[j] != '\0'; j++) {
if (!(chrs[i] >= 'A' && chrs[i] <= 'Z'))
{
printf("An invalid character was entered.\n");
break;
}
}
i++;
}
}

C - Loop ends unexpectedly

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

how can i fix these errors in c?

I keep getting these errors. Im trying to make a mine sweeper like game.
well.c: In function 'main':
well.c:170: warning: passing argument 1 of 'bombCheck' makes pointer from integer without a cast
well.c:170: warning: passing argument 3 of 'bombCheck' makes integer from pointer without a cast
well.c: In function 'fillGameBoard':
well.c:196: error: expected declaration or statement at end of input
#include <stdio.h>
#include <stdlib.h>
#define Rows 5
#define Columns 5
#define Bombs 5
void introduction(void)
{
puts("Welcome to the minefield!");
puts("In this level 2 game, you will win by choosing.");
puts("all of the viable wells and not any of the.");
puts("tool breaker spaces. In both games, there are.");
puts("20 viable spaces and 5 tool breakers!");
puts("Have fun and good luck!");
}
void fillGameBoard(char gameBoard[][Columns])
{
int i, j;
FILE *inputFile;
char gameDataFileName[30];
int yes = 0;
do
{
printf("choose your spot");
printf("\nfield1 field2\n");
scanf(" %s",&gameDataFileName);
if ((inputFile = fopen(gameDataFileName,"r")) == NULL)
{
puts("\nWrong input! Try again!");
puts("check spelling, spacing, etc. make it exact!");
}
else
{
yes = 1;
}
} while (yes == 0);
for (i=0; i<Rows; i++)
{
for (j=0; j<Columns; j++)
{
fscanf(inputFile, " %c", &gameBoard[i][j]);
}
fclose(inputFile);
return;
}
void fillUserBoard(char userBoard[][Columns])
{
int i,j; // counters
for (i=0; i<Rows; i++)
{
for (j=0; j<Columns; j++)
{
userBoard[i][j] = '~';
}
}
return;
}
void displayBoard(char board[][Columns])
{
int i, j;
printf("\n ");
for (i = 1; i <= Rows; i++)
{
printf("%d ",i+5);
}
puts("");
for (i = 0; i <=Rows; i++)
{
printf("__");
}
puts("");
for (i=0; i<Rows; i++)
{
printf("%d|",(i+1));
for (j=0; j<Columns; j++)
{
printf(" %c", board[i][j]);
}
puts("");
}
return;
}
char bombCheck (char board[][Columns], int a, int b)
{
char gameOver;
if (board[a][b] == '*')
{
puts("");
puts(" BOOM");
puts("You hit a mine.");
puts("you are deaded.\n");
puts(" GAME OVER!!\n");
gameOver = 'y';
}
else
{
gameOver = 'n';
}
return gameOver;
}
int main (void)
{
char gameBoard[Columns][Rows];
char userBoard[Columns][Rows];
char done;
char win;
char gameOver;
int count;
int i;
int col;
int row;
introduction();
do
{
done=win='n';
count=0;
fillGameBoard(gameBoard);
fillUserBoard(gameBoard);
displayboard(userBoard);
bombcheck();
do
{
displayBoard(userBoard);
printf("choose your column, numbered 1-5\n");
scanf(" %i", &col);
printf("choose your row, numbered 1-5\n");
scanf(" %i", &row);
done = bombCheck(col, row, gameBoard);
if (done='n')
{
count+1;
if (count==((Columns*Rows)-Bombs))
{
printf("you win!\n");
done='y';
}
else
{
done='n';
userBoard[col][row]=gameBoard[col][row];
}
}
} while (done != 'y');
printf("do you want to play again? y/n \n");
scanf(" %c", win);
}while (win != 'y');
return 0;
}
You're missing a brace in fillGameBoard().
for (i=0; i<Rows; i++)
{
for (j=0; j<Columns; j++)
{
fscanf(inputFile, " %c", &gameBoard[i][j]);
} /* Note closing brace! */
}
fclose(inputFile);
You're passing the arguments to bombCheck() in the wrong order.
/* Declared: char bombCheck (char board[][Columns], int a, int b) */
done = bombCheck(gameBoard, col, row);
What's with the bombcheck() call with no arguments? Note that bombcheck() is different from bombCheck(). The C programming language is case-sensitive.
For future reference, post only the minimal code snippets relevant to your question, instead of an entire program.
Case matters in C. bombcheck is not the same as bombCheck.
Argument order matters. You have declared bombCheck with (board, a, b) but are calling it with (col, row, board).
Taking the address of an array is redundant. The & is not necessary in scanf("%s",gameDataFileName);
scanf with %s is pretty unsafe. Watch what happens if you type in more than 30 characters (perhaps substantially more). Try fgets instead.
You're missing a closing brace in fillGameBoard (probably in the second inner for loop).
Your indenting is inconsistent in some places, particularly where you have left aligned return statements (and some other statements at the end of blocks).
Overall, this is a pretty good beginner program. Keep at it, and you'll get familiar with those compiler errors in no time!
There is a missing closing brace } to end the fillGameBoard function.
The number of opening and closing braces don't add up.
line 170: wrong order of arguments
line 51: missing }

Resources