I think my problem is something simple, but I'm not seeing it. I'm new to programming in C and this is an effort to see what I've absorbed, bit by bit. I think I must have not properly defined my char variable "dopt". Hope you can help. Here's the code:
#include <stdio.h>
int dbref();
int aart();
int wgame();
int calc();
int txtoc();
int amin()
{
char dopt;
printf("What should this program have the options of doing?\n");
printf("A) Reference a database?\n");
printf("B) Print ascii art?\n");
printf("C) Make a noun, pronoun, object, verb word game?\n");
printf("D) Being a calculator?\n");
printf("E) creating a text file and save it as a .c file?\n");
printf("F) or should it just terminate?\n");
scanf("%c", &dopt);
if (dopt == a || A)
{ dbref();}
if (dopt== b || B)
{ aart();}
if ( dopt==c || C)
{ wgame();}
if ( dopt==d || D)
{ calc();}
if ( dopt==e || E)
{ txtoc();}
if ( dopt==f || F)
{ return 0;}
return 1;
}
dbref()
{
printf("reference A correct");
return 2;
}
aart()
{
printf("reference B correct");
return 3;
}
wgame()
{
printf("reference C correct");
return 4;
}
calc()
{
printf("reference D correct");
return 5;
}
txtoc()
{
printf("reference E correct");
return 6;
}
As a sidenote, the printf routines in the functions are just to verify that the menu is flowing correctly.
Code like this:
if (dopt == a || A)
should be written something like this:
if (dopt == 'a' || dopt == 'A')
because a would be the name of a variable or function (which doesn't exist), and 'a' is a character literal.
Alternatively, you could consider a switch block:
switch (dopt)
{
case 'a':
case 'A':
dbref();
break;
case 'b':
case 'B':
aart();
break;
/* etc. */
default:
fprintf(stderr, "Unrecognised option!\n");
return 1;
}
a is not the same as 'a'
a is an identifier
'a' is a character
You want to match that if the contents of the char variable dopt is any of the characters. So you need to compare the ASCII values of the characters, which can be found by placing the character within a single quotes.
Therefore
if (dopt == a || A)
{ dbref();}
a and A are treated as two separate variables (names), which are not declared (at least locally) .
Thus it should be
if (dopt == 'a' || 'A')
{ dbref();}
Here 'a' and 'A' are character constants and not variable names.
BUT 'a' || 'A' is always 1 because || is logical OR operator. Therefore dopt will always be false (almost). But if you want to make the effect that if dopt is either 'a' or 'A' then call dbref () then you need to do the following:
if ((dopt == 'a') || (dopt == 'A'))
{ dbref();}
or also
if (toupper (dopt) == 'A') // similar with tolower ()
{ dbref();}
Writing dopt == a || A does not work in C. What you want is
dopt == 'a' || dopt == 'A'
In C, you have to enclose character literals with ' (otherwise they are interpreted as variables). You also can't combine the logical or, but have to type in the dopt == each time.
You want to quote your letters in the option check, otherwise they're treated as variables, and will fail to compile because they don't exist.
Related
I'm trying to do loop menu with some basic functions, everything is working fine apart of looping menu
in my opinion i have something wrong with while loop but i can't figure out what it is.
int main(void) {
char letter;
char status = 0;
printf ("--------------------------------------\n");
printf("a – Calculate the area of a rectangle\n");
printf("b – Calculate the area of a circle\n");
printf("c – Display a multiplication table\n");
printf("d – Add two numbers\n");
printf("x - exit program\n");
printf ("--------------------------------------\n");
scanf("%c",&letter);
while (status == 0)
{
if (letter == 'a' || letter == 'A')
{
}
if (letter == 'b'|| letter == 'B')
{
}
if(letter == 'c'|| letter == 'C')
{
}
if (letter == 'd'|| letter == 'D')
{
}
if(letter == 'x' || letter == 'X')
{
printf("shut down\n");
break;
}
status ++
}
return 0;
}
You need to pace a scanf(" %c",&letter); inside the loop body; otherwise, you will not get a chance to ever enter an x...
Please note the space before the %c, i.e. the " %c"-format, which captures any new line in the input buffer from a previous input.
Maybe you meant that status will be int and not char?
You should read input also in the beginning of loop, otherwise you will take only one input
After the first iteration, you advance status so it will exit the loop. Is this what you tried to achieve? I guess you meant for:
if(letter == 'x' || letter == 'X')
{
printf("shut down\n");
status ++
break;
}
Your loop will run only one time cause 'status ++' will work no matter the condition you should use it inside the x case -
if(letter == 'x' || letter == 'X')
{
printf("shut down\n");
status ++;
}
This should break your loop only after 'x' is entered.
I need to make Check whether a character is a Vowel or Consonant as function and it returns 1 if it's a vowel and returns 0 if it's consonant
That's what I've come up with
#include <stdio.h>
#include <stdlib.h>
int vowel(char c) {
int lowercase, uppercase;
lowercase = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
uppercase = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
if (lowercase || uppercase)
return 1;
else
return 0;
}
int main() {
char c;
printf("Enter an alphabet: ");
scanf("%c", &c);
vowel(c);
}
Input: a
Output: Process returned 0
Your function int vowel(char c) looks OK, though for readability and better compiler optimization opportunities I'd use a switch statement, like this:
int vowel(char c) {
switch(tolower(c)){
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return 1;
default:
return 0;
}
}
The second observation is that you seem to ignore the result of the function's execution altogether. I could only assume you were supposed to do something with it, like printing out the result. Something along these lines (instead of the v̶o̶w̶e̶l̶(̶c̶)̶;̶ code):
printf("\nThe character '%c' is %sa vowel\n", c, vowel(c) ? "" : "not ");
return type of vowel function is "int". But the function call is not storing the value. Change the function call as below.
int main() {
char c;
printf("Enter an alphabet: ");
scanf("%c", &c);
int flag = vowel(c);
printf("%d",flag); }
#include <stdio.h>
#include <stdlib.h>
int vowel(char c) {
int lowercase, uppercase;
lowercase = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
uppercase = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
if (lowercase || uppercase)
return 1;
else
return 0;
}
int main() {
char c;
printf("Enter an alphabet: ");
scanf("%c", &c);
int a=vowel(c);
if(a==1)
printf("vowel");
if(a==0)
printf("consonant");
}
Answering your questions one by one
Firstly,
what you have is a void function called vowel that takes in a char parameter.
When you declare a type of the function, what you are basically doing is telling the system what sort of return type you are expecting from this function. Since you are declaring the function void, you are expecting no return type from it hence, it does not matter what you return there.
Secondly,
when you declare the vowel function int, in your main function you have to store the value of the vowel function in a variable.
Thirdly,
the process returned 0 that you see is mainly the execution of your program saying no errors occurred.
What you probably are looking for is something like this I think,
if (lowercase || uppercase)
printf("1");
else
printf("0");
It's awesome to come up with own solutions, I would also suggest following the solutions given above as they are good coding practice.
#include<stdio.h>
int main() {
char a;
printf("enter a letter");
scanf("%c", & a);
if (a >= 'A' || a <= 'Z') {
a = a + 32;
} else if (a >= 'a' || a <= 'z') {
a = a - 32;
}
printf("%c", a);
return 0;
}
The if condition is being properly executed, but what is wrong with the else condition?
You should change your condition to
if(a>='A' && a<='Z'){
a=a+32;
}
else if(a>='a' && a<='z'){
a=a-32;
}
To check both upper and lower bounds. Otherwise, if (a>='A' || ....) will eat up all the inputs for either uppercase or lowercase letters.
Let's start with the ASCII codes of the alphabet. The uppercase letters begin with 65 for A through 97 for Z. The lower case starts with 97 for a through 122 for z.
Now, take your your conditional if(a>='A'||a<='Z'), it states all values greater than or equal to A (65) or lower than or equal to Z . This is a problem, because every ASCII code of any lowercase letter is greater than the code of A, that is, every lowercase letter is greater than A. Since this conditional uses an || (or) operator, everytime a>='A' is true, it will short-circuit and enter the body of your conditional.
In order to check for a range of letters, you should change it to:
if(a>='A' && a<='Z'){
a=a+32;
}
else if(a>='a' && a<='z'){
a=a-32;
}
Now, your conditional uses the && (and) operator, which must evaluate to true both parts, a>='A' and a<='Z', in order to enter the body of the conditional. This way, you make sure that the letter being checked, lies in the specified uppercase or lowercase ranges.
If you want to flip the case, and you entered uppercase letter, second 'if' will be bypassed because of 'else'.
Instead of || you should have used &&. This will bound the condition you are putting. Snippet shown below:
#include<stdio.h>
int main() {
char a;
printf("enter the alphabet");
scanf("%c", & a);
if (a >= 'A' && a <= 'Z') {
a = a + 32;
}
else if (a >= 'a' && a <= 'z') {
a = a - 32;
}
printf("%c", a);
return 0;
}
I'm new to C and I had written the following code:
for(i=0; i<25; ++i) {
ch=getchar();
if (ch == 'A' || ch == 'B'|| ch == 'C'|| ch == 'D'|| ch == 'a'|| ch == 'b'|| ch == 'c'|| ch == 'd'){
putchar(toupper(ch));
}
}
I expect my code to filter out the letters "a,b,c and d" AND show them as an output if and only if there is an A that can be paired with B (same for B) and C that can be paired with D. (output in uppercase)
I used for loop for this so that it would get the letters each time it enters the loop.
I do not want my code to include arrays.
An example input and expected output:
input: ATASHPPOTCBD
output: ACBD
It writes the first A because it's able to pair it with B but not the second A. Also it writes the C and D because they were able to be paired.
Some simple pseudo-code that shows a possible algorithm:
read_all_input_into_a_string();
current_A = 0;
for(each character in the string)
{
if (character == 'A')
{
++current_A;
current_B = 0;
for (each character2 in the string)
{
if (character2 == 'B')
{
++current_B;
if (current_A == current_B)
{
// Found matching A and B
}
}
}
}
}
If you should not start over from the beginning of the string when searching for a matching 'B' then just start from the position where you found the 'A'.
My program: Something is wrong
#define _CRT_SECURE_NO_WARNINGS
#include <ctype.h>
#include <stdio.h>
//Функция для проверки соответствия символов.
int ifSignsCorrect(char theChar) {
if ((theChar >= 'A' && theChar <= 'Z') || (theChar >= 'a' && theChar <= 'z') || theChar == '.' || theChar == ' ' || theChar == '*') return 1;
return 0;
}
int main() {
char string[256];
int i = 0;
//Заполняем массив
for (i = 0; i < 256; i++) {
scanf("%c\n", &string[i]);
if (string[i] == '*') break;
printf("%с\n", string[i]);
if (ifSignsCorrect(string[i]) != 1) {
printf("You used wrong characer, formating disc C (Just joking)\n");
return;
}
}
}
Three things I want to mention:
First:
You are trying to access invalid pieces of memory with this code:
int i = 0;
while (string[i - 1] != '*') {
In the first iteration you will access string[-1]. You have to solve that first.
Second:
You are defining an array of pointers in this line:
char *string[256];
use an array of characters char string[256]; instead.
Third:
You could just print like this:
printf("You used wrong characer, formating disc C (Just joking)\n");
Unless you want to define variable that will indicate this error_message, that could be cleaner some times, specially is you are going to reuse it.
Hope it helps.
You used an array of pointers instead of array of characters here:
char *string[256];
You are also accessing the array out of bounds here:
while (string[i - 1] != '*') { // here i == -1
Also a if statement after the scanf() like this would be proper:
if( string[i] == '*' )
break ;
EDIT:
Why does the program only print the character ? ?
Because the character c in the line printf("%с\n", string[i]); is actually not an ascii c
Try copying it into a program that only supports ascii. I copied it into notepad++ and set the encoding to ascii and it turned to ? :) . Must be a multilanguage support error as i see you have cyrillic enabled.