Apologies for the dumb question, I'm a bit of a beginner and am having trouble understanding why the following code will not work correctly.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int j = ' ';
int check = 0;
printf("\nPlease enter A, B, or C\n");
j = getch();
while(check == 0)
{
if(j != 'A' || 'B' || 'C')
{
printf("\nInvalid entry, please enter either an A, B, or C\n");
j = getch();
}
else
{
check = 1;
}
}
}
All I want this simple program to do is take in either A, B, or C using getch() (Yes, I need to use getch()) and use my while loop to confirm the entry actually is either an A, a B, or a C. However, I run the program, and even when I enter an A, B, or a C, the program tells me my entry is not valid. Can someone help me here and tell me what I'm doing wrong?
I have a feeling this has to do with the fact that it reads in the character as an ASCII integer, but I'm really not sure how to fix this.
if(j != 'A' || 'B' || 'C')
is equivalent to
if(j != 'A' || 'B' != 0 || 'C' != 0)
Both 'B' and 'C' have non-zero value so the condition will always evaluate true.
I think you want to check that j isn't any of the values listed. If so, the line should be
if(j != 'A' && j != 'B' && j != 'C')
Do the following replacements:
int j = ' '; /* to */ char j = ' ';
if(j != 'A' || 'B' || 'C') /* to */ if(j != 'A' && j != 'B' && j != 'C')
j = getch(); /* to */ j=getchar();
Also, for getchar() to work, include <conio.h> if required.
Related
So, my code actually works perfectly when I use function that checks for special characters in string by explicitly giving symbols:
int isSpecialCharacter(char str[], int n)
{
for(int i=0; i<n;i++)
{
if (str[i] == '!' || str[i] == '#' || str[i] == '#' || str[i] == '$' || str[i] == '%' || str[i] == '^' || str[i] == '(' || str[i] == ')')
{
return 1;
}
return 0;
}
}
However, in the below code I am not able to get my code to find special characters in string using ASCII values. I want to understand what am I doing wrong. In the below code, I have my main() also included that prompts the user to input string.
#include <stdio.h>
#include <string.h>
char str[30][30];
char test[100];
int myindex = 0;
int isSpecialCharacter(char str[], int n)
{
for(int i=0; i<n;i++)
{
if (str[i] == 33 || str[i] == 35 || str[i] == 36 || str[i] == 37 || str[i] == 40 || str[i] == 41 || str[i] == 64)
{
return 1;
}
return 0;
}
}
int main()
{
printf("Please enter 10 strings below: \n");
while(myindex < 10)
{
printf("Enter string %d: ", myindex+1);
fgets(str[myindex], 500, stdin);
strcpy(test, str[myindex]);
int t_size = strlen(test);
if (strlen(str[myindex])<2||strlen(str[myindex])>26)
{
printf("Enter string that is between 2 and 25");
continue;
}
else if(isSpecialCharacter(test, t_size) == 1)
{
printf("Your string has some special characters. \n");
continue;
}
else
{
myindex++;
}
}
return 0;
}
EDIT:
I have included the variable declarations and replaced the code where I use symbols to check for special characters. Thank you.
EDIT2:
These are the characters that I want to look for: : ’!’, ’#’, ’#’, ’$’, ‘%’, ‘^’, ’(’, or ’)’. Not spaces.
Both your functions won't work as you've written them.
The main problem is that the for loop returns after each loop cycle, so you never check beyond the first cycle.
You should move the return 0 statement to the end of the function, then it will work as expected.
int isSpecialCharacter(char str[], int n)
{
for (int i = 0; i < n; i++)
{
if (str[i] == 33 || str[i] == 35 || str[i] == 36 || str[i] == 37 || str[i] == 40 || str[i] == 41 || str[i] == 64)
{
return 1;
}
}
return 0;
}
Test
I've tested the solution with the following input:
test1
test2
test)
test(
test3
test4
test5
test#
test6
test7
test!
test8
test9
test10
And it works. You can see the result there: https://godbolt.org/z/67Px14z75
As suggested from other users in the comment section, using decimal values to refer to characters is a bad practice™ and you should stick with the '#' notation.
Your return 0; is incorrect:
int isSpecialCharacter(char str[], int n) {
for(int i=0; i<n;i++)
{
if (str[i] == '!' || str[i] == '#' || str[i] == '#' || str[i] == '$' || str[i] == '%' || str[i] == '^' || str[i] == '(' || str[i] == ')')
{
return 1;
}
return 0;
}
}
On the very first loop, your function returns either 1 or 0. You only want to return 0 (false) if the loop completes without finding the character you're looking for.
int isSpecialCharacter(char str[], int n)
{
for(int i=0; i<n;i++)
{
if (str[i] == '!' || str[i] == '#' || str[i] == '#' || str[i] == '$' || str[i] == '%' || str[i] == '^' || str[i] == '(' || str[i] == ')')
{
return 1;
}
}
return 0;
}
I'm not going to try to write your code...
if( isSpecialCharacter()
is equivalent to:
if( strpbrk( test, "abqmz" ) != NULL )
(except that the latter has been proven to work...)
If a, b, q, m, z appear in the string, then the if condition is true...
Learn the standard library instead of spending time badly reinventing it...
EDIT:
Here is how an experienced programmer might write that functionality now that you've decoded the decimal ASCII values. (Don't expect the next programmer who reads your code to reach for their ASCII table...)
char spcl[] = "!##$%^()";
if( strpbrk( test, spcl ) != NULL ) {
// Do something because condition is true
NB: if you need to make either \ or " special inside a string, you must 'escape' either of those characters with an 'extra' backslash. Eg:
char spcl[] = "\\!##$%^(\")"; // notice '\\' and '\""
If that looks too much like "bad language", you can construct your own string (ENSURING(!) that it is null terminated.)
char spcl[] = { '\\', '!', '#', '#', '$', '%', '^', '(', '\"', ')' '\0' };
And...
char str[30][30];
/* Skipping ahead */
printf("Enter string %d: ", myindex+1);
fgets(str[myindex], 500, stdin); // 500!!! ????
is simply looking for trouble...
The position of "return 0" is not correct.
It should come after the end of "for loop"
For instance, in a sentence such as
Its a great day. Right?
I want to keep reading until I reach a non-letter character, call my helper function on each string created and print the rest unchanged.
This is what I have so far but it only prints the first letter numerous times
void string_create(void) {
char word[1000+1] = {0};
int i = 0;
int j=0;
char c = 0;
while (scanf("%c", &c) == 1) {
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
word[i] = c;
i++;
}
else {
printf("%s", word);
i=0;
printf("%c", c);
}
}
}
In the end for now, without going into details of the helper function, it should simply print the original sentence unchanged.
Current output:
Its ats great dayat.dayat Right?Right
The problem is here (infinite loop) :
while((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
Use if instead of while.
Try this,
#include <stdio.h>
void string_create(void)
{
char word[1000+1] = {0};
int i = 0;
char c = 0;
scanf("%c",&c);
while ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
{
word[i++]=c;
while((c=getchar()!='\n')&&(c!=EOF)); //to remove white space
scanf("%c",&c);
}
printf("%s",word);
}
int main()
{
string_create();
return 0;
}
Output:
q
w
e
r
t
y
1
qwerty
Process returned 0 (0x0) execution time : 8.205 s
Press any key to continue.
you can also give new line(enter) instead of 1
you can also use this
scanf("%1000[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]",word);
it only read letters
I have no idea what i'm doing wrong here, but I'm trying to make a vertical histogram program based on the length of strings input through the commad line using getchar() (one of The C Programming Language excercises), but something seems to be going wrong when I run it. The function printgraph() is supposed to print the histogram using the for loops shown by printing the graph, graph[][] line by line, where j increments the y axis and i increments the x axis. However, when I run this, the graph doesn't print when it reaches this line of code. I've revised the code and gone over it many times, and still haven't a clue. I know that this may also be a trivial question to some, and I apologize that I lack much experience, but all help is appreciated.
#include <stdio.h>
char graph[11][11];
void printgraph(){
int i, j;
char graph[11][11];
for(j = 0; j<=10; j++){
for(i = 0; i<=10; i++){
putchar(graph[i][j]);
}
printf("\n");
}
}
int main(){
char c, graph[11][11];
int i, j, onoroff, numchar[10];
for(i = 10; i>=0; i--)
graph[0][i] = i;
for(j=10;j>=0; j--)
graph[j][0] = j;
for(j=0;j<=9;i++)
numchar[j] = 0;
onoroff = 1;
i = 0;
while(graph[1][10] != 'O' || graph[2][10] != 'O' || graph[3][10] != 'O' || graph[4][10] != 'O' || graph[5][10] != 'O' || graph[6][10] != 'O' || graph[7][10] != 'O' || graph[8][10] != 'O' || graph[9][10] != 'O' ||graph[10][10] != 'O'){
while((c = getchar()) != EOF){
printgraph();
if(c == ' '|| c == '\n' || c == '\t'){
if(onoroff == 1){
numchar[i]++;
graph[i][numchar[i]+1] = 'O';
}
onoroff = 0;
i = 0;
}else if(onoroff == 1){
i++;
}else if(onoroff == 0){
onoroff = 1;
i++;
}
}
}
return 0;
}
It never reaches the printgraph function since you are getting stuck in the third for loop.
for(j=0;j<=9;i++)
numchar[j] = 0;
You are incrementing i but testing j
Also see the answer from NPToita
it's because you have 3 variables named graph;
the global graph variable is never used because the main function has its own local variable graph which it writes to and printgraph has its own version of graph variable which it reads from.
can you try deleting the graph variables declarations from the main and printgraph functions and see what happens?
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.
I have the following function
int namecomp(char c);
Part of the function code
else if (c == 'b' || 'B')
i=2;
The way I am calling it in main()
j= namecomp(s);
and s is defined as char s = 'B';
There is an error and whenever I am trying to use j the value is always 1 in the main. Please help me to know where exactly the error is. Thanks!
EDIT:Sorry Folks none of it worked., I am posting the complete code for help
int main (int argc, char* argv [])
{
int i;
int j;
char s = 'B';
j= namecomp(s);
printf ("%d",j);
}
int namecomp(char c)
{
int i;
if (c == 'a'||'A')
i=1;
else if ((c == 'b' || c == 'B'))
i=2;
return i;
}
c == 'b' || 'B'
always evaluates to 1, because it's parsed as
(c == 'b') || 'B'
I'm betting you want
(c == 'b') || (c == 'B')
This
(c == 'b' || 'B')
Should be:
(c == 'b' || c == 'B')
Otherwise, you're testing this:
((c == 'b') || 'B')
Which is the same as
((c == 'b') || true)
since 'B' is non-zero.
Remember that the logical and/or symbols can't be used inside a logical test, only to join logical tests together.
You wrote
(c == 'b' || 'B') // this can be ( (c=='b') || 'B') in your compiler
Did you mean
(c == ('b' || 'B'))
or
( (c == 'b') || (c=='B') )
you should use the latter.
You should approach these conditions as a paranoid with paranthesis to make sure it satisfies your conditions. Then you can try without paranthesis if it works for every condition.
c == 'b' || 'B' is always evaluate to 1 because 'B' is a nonzero value, so the second operand is always true.
You need to test your condition both.
if (c == 'b' || c == 'B')