My code seems fine, but I get this warning (warning: comparison between pointer and integer), what is the best solution to solve this problem?
I have already used double notation marks for (char exit = "E"), also used the same thing with while but the same problem.
#include <stdio.h>
int main()
{
char c[1];
char exit = 'E';
while (c != exit)
{
printf("Enter a character\n\n");
scanf("%s", c);
printf("your character is : %s\n-------------------\n", c);
}
}
#include <stdio.h>
int main()
{
char c[1];
char exit = 'E';
while (c != exit) // here ...
{
printf("Enter a character\n\n");
scanf("%s", c);
printf("your character is : %s\n-------------------\n", c);
}
}
you are trying to compare a char to the pointer the array c decays to. What you perhaps wanted to do is to compare the first character of the array to the character exit:
while (c[0] != exit)
But that still doesn't make much sense since c is uninitialized and the user not yet had a chance to make any input. Better use a do ... while-loop:
#include <stdio.h>
int main()
{
char c[1];
char exit = 'E';
do {
printf("Enter a character\n\n");
scanf("%s", c);
printf("your character is : %s\n-------------------\n", c);
} while (c[0] != exit);
}
Next thing is, that scanf("%s", c); could fail (yes unlikely, but possible). And the user could enter more characters than there is room for in the array c. You should never use scanf() whithout checking the return value nor "%s" without specifying a WIDTH for the conversion specifier to limit the characters put into the array.
When reading a string you need memory for WIDTH characters + a terminating '\0'. So if you want to read a string of one character, the array has to have at least 2 elements:
#include <stdlib.h
#include <stdio.h>
int main()
{
char c[2];
char exit = 'E';
do {
printf("Enter a character\n\n");
while (scanf("%1s", c) != 1 ) {
fputs("Input error!\n");
return EXIT_FAILURE;
}
printf("your character is : %s\n-------------------\n", c);
} while (c[0] != exit);
}
But if you only want to read one character you are better off with getchar():
#include <stdio.h>
{
int ch;
while (printf("Enter a character\n\n"),
(ch = getchar()) != EOF && ch != 'E')
{
printf("your character is: %c\n-------------------\n", (char) ch);
}
}
i believe this is what you are trying to do.
warning is because you have not initialzed your character and also you were comparing address of character to character value.
#include <stdio.h>
int main()
{
char c[1];
char exit = 'E';
while ((c[0]=getchar()) != exit)
{
if(c[0]==EOF)break;
printf("your character is : %c\n",c[0]) ;
}
printf("ended");
}
Related
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
char out[] = "exit";
do {
printf("Enter a string: ");
scanf("%s", str);
// some if else statement here
} while (toupper(str[3]) != toupper(out[3]));
}
I put the index 3 because if I put the index 0 there, the code will terminate if the entered string starts with letter e. I tried the while loop but it does not work for me. Also I want to print a prompt message that says "detected terminate keyword" after entering the word "exit" and then terminates the loop.
You will also notice the toupper() function. I used it there because I want my loop to be case insensitive, so regarless of lowercase or uppercase or combination of both, the loop should terminate when the word "exit" is entered.
toupper(str[3]) != toupper(out[3]) will compare the upper case 4th letter of str and out, so the loop will iterate till str[3] is 'T'. You want to use strcasecmp(str, out) instead. Remember to #include <strings.h>.
There are multiple problems:
it is confusing for a function isPalindrome() to return 0 for true.
to avoid undefined behavior on negative char values, a char argument to toupper should be cast as (unsigned char).
the test for the exit keyword is incorrect. You exit if the fourth letter is a t or a T. You should use strcasecmp to test for the exit word.
scanf("%s", str) has potential undefined behavior if the user enters a word with more than 99 bytes. Use scanf("%99s", str) and test the return value: it must be 1 for a successful conversion.
instead of a confusing do / while loop, use a for (;;) loop (also known as for ever loop), and test for 2 exit conditions: scanf() failure to read a word and reading the word exit.
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int isPalindrome(const char *str) {
size_t len = strlen(str);
for (size_t i = 0; i < len; i++) {
if (toupper((unsigned char)str[i]) != toupper((unsigned char)str[len - i - 1]))
return 0;
}
return 1;
}
int main() {
char str[100];
for (;;) {
printf("Enter a string: ");
if (scanf("%99s", str) != 1)
break;
if (!strcasecmp(str, "exit"))
break;
if (isPalindrome(str)) {
printf("%s is a palindrome!\n\n", str);
} else {
printf("%s is not a palindrome!\n\n", str);
}
}
return 0;
}
I put the index 3 because if I put the index 0 there, the code will terminate if the entered string starts with letter e
Exactly, and the code:
while (toupper(str[3]) != toupper(out[3])
Suffers from the same problem, any input with a t as its 4th character index 3 will match and the loop will end, you are comparing a specific character of the string, not the string itself. You can use strcasecmp to assess if the input is indeed exit and ignore casing.
Furthermore using %s specifier is not good, you run the risk of overrunning the destination buffer. You should use a width, %99s for a 100 characters buffer to leave space for the nul byte, if possible consider using fgets instead.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
char str[100];
char out[] = "exit";
do {
printf("Enter a string: ");
scanf(" %99s", str); // space before specifier to clean leading whitespaces
// some if else statement here
} while (strcasecmp(str, out) != 0);
puts("Detected terminate keyword. Goodbye!");
}
char *removeLastChar(char *str, char ch)
{
size_t len;
if(str)
{
len = strlen(str);
if(str[len - 1] == ch) str[len -1] = 0;
}
return str;
}
char *strlwr(char *str)
{
char *wrk = str;
if(str)
{
while(*wrk)
{
*wrk = tolower((unsigned char)*wrk);
wrk++;
}
}
return str;
}
int main(void)
{
char str[100];
const char *out = "exit";
int x = 0;
do
{
printf("Enter a string: ");
if(!fgets(str, sizeof(str), stdin)) break;
removeLastChar(str, '\n');
printf("You entered: \"%s\"\n:", str);
} while (strcmp(strlwr(str), out));
}
#include <stdio.h>
#include <conio.h>
#define max 100
void compare(char *name,char* input);
int main()
{
int i=0;
char name[max]="santosh";
char input[max];
printf("enter the password\n");
while((input[i]=getchar())!='\n'){
i++;
}
input[i]='\0';
compare(name,input);
return 0;
}
void compare(char *name,char* input){
while((*name==*input)&&(*name!='\0'&&*input != '\0')){
*name++;
*input++;
}
if(*name=='\0'&&*input=='\0')
printf("Correct Password");
else
printf("Incorrect Password");
}
This Program is getting crashed in vs code but when I use getchar() instead of getch() or getche() all is working fine.
Why it is not working with getch() and how it will run as I want user to insert a password and thus want to use getch() not getchar().
First of all #define max generates a warning "macro redefinition", so change that.
The second problem is that getch() and getche do not convert the Enter key to 'newline' \n but to 'return' \r
The third problem is that instead of incrementing the pointers, you are incrementing what they point to.
Here is the corrected code:
#include <stdio.h>
#include <conio.h>
#define MAXX 100 // fixed macro name collision
void compare(char *name, char* input);
int main(void) // corrected definition
{
int i = 0;
char name[MAXX] = "santosh";
char input[MAXX];
printf("enter the password\n");
while((input[i] = getche()) != '\r') { // fixed '\n' check
i++;
}
input[i] = '\0';
compare(name, input);
return 0;
}
void compare(char *name,char* input){
while(*name == *input && *name != '\0' && *input != '\0') {
name++; // fixed pointer increment
input++; // fixed pointer increment
}
if(*name == '\0' && *input == '\0')
printf("Correct Password\n");
else
printf("Incorrect Password\n");
}
Finally you should also check i does not exceed the array bounds. The strings seem long enough, but not for players who try to break the program.
I have written this code but I have a little problem with it.
This code should get a string and check whether this string contains all the alphabet letters...
If it doesnt the output is "Not a pangramma!".
If it does "PanGramma!".
The probem is that I want it to count also the nuumber of the spaces between the words. But when the input is string with at least one space the output will always be "Not a PanGramma!", even if it contains all the alphabet letters.
Can someone please help me?
#include <stdio.h>
char UpCase (char c);
int isPangram (char *str);
int main()
{
char str[100];
printf("Please enter yout string: \n");
scanf("%s", str);
if (isPangram (str) == 1)
{
printf("PanGramma!\n");
}
else
{
printf("Not a PanGramma!\n");
}
return 0;
}
char UpCase (char c)
{
if (c>='a' && c<='z')
{
return c-'a'+'A';
}
return c;
}
int isPangram (char *str)
{
int i=0;
int hist[27]={0};
while (str[i] !=0)
{
str[i]=UpCase(str[i]);
if (str[i] == ' ')
{
hist[26]++;
}
else
{
hist[str[i] - 'A']++;
}
i++;
}
for (i=0; i<26; i++)
{
if(hist[i] == 0)
{
return 0;
}
}
return 1;
}
Your problems comes from the usage of scanf function: it does stops at each white space it catch.
From man scanf:
%s
Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.
To make your program to work, you can use fgets function:
int main()
{
char str[100];
printf("Please enter yout string: \n");
fgets(str, sizeof str, stdin);
if (isPangram (str) == 1)
{
printf("PanGramma!\n");
}
else
{
printf("Not a PanGramma!\n");
}
return 0;
}
If you want to know more on scanf function, you can read A beginners' guide away from scanf(). It will also tell you why scanf could cause a buffer overflow in your code.
Thank you guys!
I have used this
scanf ("%[^\n]%*c", str);
thanks once again for your help!
I currently have a homework assignment and I used gets.
The professor said I should be using getchar instead.
What is the difference?
How would I change my code to use getchar? I can't seem to get it right.
code:
#include <stdio.h>
#include <string.h>
#include <strings.h>
#define STORAGE 255
int main() {
int c;
char s[STORAGE];
for(;;) {
(void) printf("n=%d, s=[%s]\n", c = getword(s), s);
if (c == -1) break;
}
}
int getword(char *w) {
char str[255];
int i = 0;
int charCount = 0;
printf("enter your sentence:\n"); //user input
gets(str);
for(i = 0; str[i] != '\0' && str[i] !=EOF; i++){
if(str[i] != ' '){
charCount++;
} else {
str[i] = '\0'; //Terminate str
i = -1; //idk what this is even doing?
break; //Break out of the for-loop
}
}
printf("your string: '%s' contains %d of letters\n", str, charCount); //output
strcpy(w, str);
// return charCount;
return strlen(w); //not sure what i should be returning.... they both work
}
gets() was supposed to get a string from the input and store it into the supplied argument. However, due to lack of preliminary validation on the input length, it is vulnerable to buffer overflow.
A better choice is fgets().
However, coming to the usage of getchar() part, it reads one char at a time. So basically, you have to keep reading from the standard input one by one, using a loop, until you reach a newline (or EOF) which marks the end of expected input.
As you read a character (with optional validation), you can keep on storing them in str so that, when the input loop ends, you have the input string ready in str.
Don't forget to null terminate str, just in case.
How can I check whether there are numbers in char provided by user in C language?
Last line of C code to change :):
char name;
do{
printf("What's your name?\n");
scanf("%s\n", name);
}
\\and here's my pseudocode:
while (name consist of a sign (0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9));
Here is a different approach that tests for specified chars in one function call.
#include <stdio.h>
#include <string.h>
int main()
{
char name[100];
char charset[]= "-+0123456789";
int len;
do {
printf("What's your name?\n");
scanf("%s", name);
len = strlen(name);
}
while (strcspn(name, charset) != len);
printf ("Your name is '%s'\n", name);
return 0;
}
You need to include ctype.h and use the isdigit() function.
But you also have another porblems in the posted code, "%s" specifier expects a char pointer, and you are passing a char, may be what you need is a char array like this
#include <stdio.h>
#include <ctype.h>
int main()
{
char name[100];
int i;
do {
printf("What's your name?\n");
scanf("%s\n", name);
}
/* and here's my pseudocode: */
i = 0;
while ((name[i] != '\0') &&
((isdigit(name[i]) != 0) || (name[i] == '-') || (name[i] == '+')))
{
/* do something here */
}
}
remember to include ctype.h and stdio.h
Use isdigit();
Prototype is:
int isdigit(int c);
Similarly to check the character is alphabet
Use
isalpha()
Once you get the string from the user, loop on it to search for correct input. (i.e. to see if there is a digit embedded in a collection of alpha characters). Something like this will work:
Assume userInput is your string:
int i, IsADigit=0;
int len = strlen(userInput);
for(i=0;i<len;i++)
{
IsADigit |= isdigit(userInput[i]);
}
The expression in the loop uses |=, which will detect and keep a TRUE value if any of the characters in the string are a digit.
There are many other methods that will work.
And the following family of character tests will allow you to do similar searches for other types of searches etc.:
isalnum(.) //alphanumeric test
isalpha(.) //alphabetic test
iscntrl(.) //control char test
isalnum(.) //decimal digit char test
isxdigit(.) //hex digit char test
islower(.) //lowercase char test
...The list goes on