I'm writing code which checks if an array is palindrome or not:
Write a program that reads a message, then checks whether it's a palindrome
(the letters in the message are the same from left to right as from right to left):
Enter a message: He lived as a devil, eh?
Palindrome
Enter a message: Madam, I am Adam.
Not a palindrome
When I have entered He lived as a devil, eh?,
it gives me the output Not a palindrome,
but the real output should be palindrome.
Below code is what I have tried so far.
#include <stdio.h>
#include <ctype.h>
#define MAX_LEN 100
int main(void) {
char message[MAX_LEN];
char c, *p = message, *q;
printf("Enter a message: ");
while ((c = toupper(getchar())) != '\n' & p < message + MAX_LEN) {
if (isalpha(c))
*p++ = c;
}
p--;
for (q = message; q < p; q++, p--) {
if (*p != *q) {
printf("Not a palindrome\n");
return 0;
}
}
printf("Palindrome\n");
return 0;
}
For starters you should declare the variable c as having the type int. The user can interrupt the input process in which case the function getchar returns integer value EOF and you should check whether this occurred.
char *p = message, *q;
int c;
There is a bug in the condition of the while statement
while ((c = toupper(getchar())) != '\n' & p < message + MAX_LEN) {
Instead of the bitwise operator & you have to use the logical AND operator &&.
As I already have said you should check in the condition of the while statement whether the user interrupted the input. For example
while ( p < message + MAX_LEN && ( c = toupper(getchar())) != EOF && c != '\n') {
if (isalpha(c))
*p++ = c;
}
The argument of a call of toupper or isalpha should be converted to the type unsigned char. Otherwise in general without the casting such a call can invoke undefined behavior.
It is desirable not to exclude from an entered string numbers. SO it is better at least to call the function isalnum instead of the function isalpha.
The user can enter an empty string in this case this decrement of the pointer
p--;
also can invoke undefined behavior.
And it is better when a program has one point to exit.
The program can look the following way
#include <stdio.h>
#include <ctype.h>
#define MAX_LEN 100
int main(void)
{
char message[MAX_LEN];
printf( "Enter a message: " );
char *p = message;
for ( int c; p < message + MAX_LEN && ( c = getchar() ) != EOF && c != '\n'; )
{
if( isalnum( ( unsigned char )c ) )
{
*p++ = toupper( ( unsigned char )c );
}
}
int palindrome = 1;
if ( p != message )
{
for ( char *q = message; palindrome && q < --p; ++q )
{
palindrome = *q == *p;
}
}
printf( "The entered message is %spalindrome\n",
palindrome ? "" : "not " );
return 0;
}
Its output might look for example like
Enter a message: He lived as a devil, eh?
The entered message is palindrome
or like
Enter a message: Madam, I am Adam
The entered message is not palindrome
Pay attention to that instead of using a loop with numerous calls of the function getchar you could use only one call of the function fgets
fgets( message, sizeof( message ), stdin );
or
if ( fgets( message, sizeof( message ), stdin ) != NULL )
{
// check whether the entered string is a palindrome
}
Before check the palindrome you have to remove white spaces and punctuation marks. For an example if you use civic?, it is not palindrome because of ?. In the other hand if you use civ ic, it is not palindrome because of white space. There for
Convert all letters to uppercase or lowercase.
Remove white spaces.
remove punctuation marks.
Check palindrome or not.
You can do it by using # include <string.h>
First thing is you have to use scanf() which accept string with white space.
printf("Enter a string = ");
scanf("%[^\n]%*c", word);
Then you have to convert that string to Uppercase or Lowercase because a != A. We know civic is a palindrome but Civic is not a palindrome('Civic != civiC) because Uppercase letters have different ASCII values and Lowercase letters have different ASCII values.
(a - z) -: 97 - 122
(A - Z) -: 65 - 90
In my case I have converted lowercase to uppercase.
while(strlen(word) >= i)
{
if(word[i] >= 97 && word[i] <= 122)
{
word[i] = word[i] - 32;
}
i++;
}
Another case is your if you enter civ ic with white space, it's palindrome word is ci vic. You can see civ ic != ci vic. There for you have to remove white spaces in your program. And also you have to remove punctuation marks because if you use civic, it's reversed word is ,civic'. You can seecivic, != ,civic`.
int len = strlen(word);
while(a < len)
{
for(i = 0; i < len; i++)
{
if(word[i] == ' ' || !(word[i] >= 'A' && word[i] <= 'Z'))
{
for(j = i; j < len; j++)
{
word[j] = word[j+1];
}
len--;
}
}
a++;
}
Final thing is we have to revers our string and need to check if our reversed string is equal to our original string. If it is true our String is palindrome. If it is false our String is not a palindrome.
for(i = 0; i < len; i++)
{
if(word[i] == word[len - 1])
{
len--;
}
else
{
printf("%s is not a palindrome\n", word);
return 0;
}
}
printf("%s is a palindroeme\n", word);
This the full code after you merging above parts
# include <stdio.h>
# include <string.h>
int main (void)
{
char word[100];
int i = 0;
int j, x = 0;
int a = 0;
printf("Enter a string = ");
scanf("%[^\n]%*c", word);
while(strlen(word) >= i)
{
if(word[i] >= 97 && word[i] <= 122)
{
word[i] = word[i] - 32;
}
i++;
}
printf("After converting it to uppercase = %s\n", word);
int len = strlen(word);
while(a < len)
{
for(i = 0; i < len; i++)
{
if(word[i] == ' ' || !(word[i] >= 'A' && word[i] <= 'Z'))
{
for(j = i; j < len; j++)
{
word[j] = word[j+1];
}
len--;
}
}
a++;
}
printf("After removing spaces = %s\n", word);
for(i = 0; i < len; i++)
{
if(word[i] == word[len - 1])
{
len--;
}
else
{
printf("%s is not a palindrome\n", word);
return 0;
}
}
printf("%s is a palindroeme\n", word);
return 0;
}
First test Output -:
Enter a string = He lived as a devil, eh?
After converting it to uppercase = HE LIVED AS A DEVIL, EH?
After removing spaces = HELIVEDASADEVILEH
HELIVEDASADEVILEH is a palindroeme
Second test Output -:
Enter a string = Madam I am Adam.
After converting it to uppercase = MADAM I AM ADAM.
After removing spaces = MADAMIAMADAM
MADAMIAMADAM is not a palindrome
Related
I have an assignment that requires me to write a function to take in an array containing an English sentence and return the length of the longest word in that sentence. This is the code I have so far:
int longWordLength(char *s); // Function prototype
int main() {
char str[80], *p;
printf("Enter a string: \n");
fgets(str, 80, stdin);
if (p = strchr(str,'\n'))
*p = '\0'; //converts newline to null
printf("longWordLength(): %d\n", longWordLength(str));
return 0;
}
int longWordLength(char *s) {
int count = 0, max = 0;
while (*s++ != '\0') {
if ((*s >= 'a' && *s <= 'z') || (*s >= 'A'&& *s <= 'Z')) {
count++;
} else {
if (count > max) {
max = count;
count = 0;
} else
count = 0; // word is not the longest
}
}
return max;
}
I have tried for a long time to diagnose the issue but to no avail.
This works with certain test case like:
Test Case 1:
Enter a string:
I am happy.
longWordLength(): 5
but for a test case like
Test Case 4:
Enter a string:
Hello
longWordLength(): 4 <- it prints 4 instead of 5.
I am not allowed to use any library other than the <string.h> as it is for my school assignment. Seeking anyone's kind guidance on my issue as I really can't seem to figure out the issue. Thank you in advanced.
The problem is in while (*s++ != '\0') {: you increment the string pointer before testing the character it points to. Just change to code to:
for (; *s != '\0'; s++) {
...
Note however that the last word will not be tested the maximum length if it is not followed by some separator such as a space or a newline, which you would have stripped.
Note that stripping the trailing newline is not required for longWordLength() to determine the correct count.
Here is a modified version:
#include <stdio.h>
int longWordLength(const char *s); // Function prototype
int main() {
char str[80];
printf("Enter a string: \n");
if (!fgets(str, sizeof str, stdin))
return 1;
// no need to strip the newline for this test:
printf("longWordLength(): %d\n", longWordLength(str));
return 0;
}
int longWordLength(const char *s) {
int count = 0, max = 0;
for (;; s++) {
if ((*s >= 'a' && *s <= 'z') || (*s >= 'A'&& *s <= 'Z')) {
count++;
} else {
if (count > max) {
max = count;
}
if (*s == '\0')
break;
count = 0; // reset the counter for the next word
}
}
return max;
}
I wrote a very simple Hangman game that requests user input then makes the user guess up to six times.
The first letter of the word is always shown and if the user inputs the same letter that has already been uncovered it is not seen as a mistake,
I want to improve my code to make it accept lowercase input if the hangman string consists of Uppercase letters.
For example if the input string is "HELLO" and the user sees this H_____ on the console and he inputs lowecase 'e' then the letter should be uncovered and printed as a capital letter as the input string.
So after the user inputs e the output should look like this HE___
However with the way I implemented it just converts all uppercase Letters to lowercase Letters.
How can I make the code accept lowercase userinput and print out Uppercase user input if a Uppercase letter is in the string?
Thanks for any help
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
char hangmanWord[100], tempWord[100];
char hangmanOutput[100];
int wrongTry = 6 , matchFound = 0;
int tries = 0;
int counter = 0 , position = 0, winner, length , i;
char alphabetFromUser;
scanf("%s",hangmanWord);
getchar();
length = strlen(hangmanWord);
for( i = 1; i < length ; i++)
{
hangmanOutput[i] = '_';
hangmanOutput[length] = '\0';
}
for(i = 0 ; i < length ; i++)
{
if(i==0){
printf("%c",hangmanWord[0]);
}
printf("%c",hangmanOutput[i]); //line output
if(i==length-1){
printf("(%d)",tries);
}
}
while(wrongTry != 0) /**while loop for exiting the program when no try left**/
{
matchFound = 0;
putchar('\n');
printf("letter: ");
scanf("%c",&alphabetFromUser);
fflush(stdin);
if (matchFound != 2)
{
for(counter=0;counter<length;counter++) /**for loop to check whether player input alphabet exists or not in the word**/
{
if(hangmanWord[counter]>= 'A' && hangmanWord[counter] <= 'Z'){
hangmanWord[counter] = tolower(hangmanWord[counter]);
}
if(alphabetFromUser==hangmanWord[counter])
{
matchFound = 1;
}//end of if()
}//end of
if(matchFound == 0) /**in case of wrong guess**/
{
wrongTry--;
tries++;
}//en
else
{
for(counter = 0; counter < length; counter++)
{
matchFound = 0;
if(alphabetFromUser == hangmanWord[counter])
{
position = counter ;
matchFound = 1;
}//end of if
if(matchFound == 1)
{
for(i = 0 ; i < length ; i++)
{
if( i == position)
{
hangmanOutput[i] = alphabetFromUser; /**Put the alphabet at right position**/
}
else if( hangmanOutput[i] >= 'a' && hangmanOutput[i] <= 'z' ) /** If the position already occupied
by same alphabet then no need to
fill again EASY!! and continue */
{
continue;
}
else
{
hangmanOutput[i] = '_'; /** Put a underscore at not guessed alphabet position **/
}
}
tempWord[position] = alphabetFromUser; /**put the alphabet in another char array to check with the original word**/
tempWord[length] = '\0';
/**put the NULL character at the end of the temp string**/
winner = strcmp(tempWord+1,hangmanWord+1); /**upon True comparison it will return 0**/
if(winner == 0) /**if the player guessed the whole word right then he/she is the WINNER**/
{
for(i = 0 ; i < length ; i++)
{
if(i==0){
printf("%c",hangmanWord[0]);
}
printf("%c",hangmanOutput[i+1]); //line output
if(i==length-1){
printf("(%d)",tries);
}
}
getchar();
return 0;
}//end of inner if
}//end of outer if
}//end of for loop
}//end of else
} // end of if(matchFound != 2) condition
for(i = 0 ; i < length ; i++)
{
if(i==0){
printf("%c",hangmanWord[0]);
}
printf("%c",hangmanOutput[i+1]); //line output
if(i==length-1){
printf("(%d)",tries);
}
}
getchar();
}
if(wrongTry <= 0) /**if the player can not guess the whole word in 5 chaces**/
{
putchar('\n');
printf("DEAD\n");
return 0;
}
getchar();
return 0;
}
Looking at ascii table, the lower case letters from a-z are from 0x6_, to 0x7_ and the upper case ones from 0x4_ to 0x5_, which means that all we have to do is to toggle off the second bit of the second nibble in order to convert a lowercase letter to an uppercase letter.
(a) a-z are as follows 0110 xxxx, 0111 xxxx
(b) A-Z are as follows 0100 xxxx, 0101 xxxx
Let's assume that we have the character 'a', which is 0110 xxxx. If we use the AND bitwise with 0x5F => 0110 xxxx & 0101 xxxx => 0100 xxxx => 'A'
char upper(char ch) {
return(ch & 0x5F);
}
Now that we have the function, we can use it. Looking at your code, you are checking the hangman array twice in case the user has typed in a lower case letter or a uppercase letter so instead of doing that we could do that once
int32_t right_letter;
int32_t tries;
int32_t win;
right_letter = 0;
/* since one letter is already discovered */
win = length - 1;
while(wrongTry != 0) {
/* read from user */
for(counter = 0; counter < length; ++counter) {
if(hangmanOutput[counter] == '_'){
if(upper(alphabetFromUser) == upper(hangmanWord[counter])) {
hangmanOutput[counter] = hangmanWord[counter];
right_letter = 1;
++win;
}
}
if(win + 1 == length)
/* win */
wrongTry -= !right_letter;
right_letter = 0;
}
I haven't tested the code, but it should work. Try to understand what I have changed and why.
EDIT: #Andrew Henle had mentioned in the comments that the OP hadn't specified the character set, therefore I assumed that It's ASCII.
For an ASCII only input, it is no brainer....Just exploit the fact that char type in C can in fact be used as int and do the maths.
#include <stdio.h>
#include <stdlib.h>
int main(){
char ch;
printf("letter : ");
ch = getc(stdin);
if (ch >= 'a' && ch <= 'z')
ch -=32;
else if (ch >= 'A' && ch <= 'Z')
ch += 32;
printf("output : %c\n", ch);
return 0;
}
Another version is given below. You can replace lower_case and upper_case with any other alphabet you want and boom, it will work.
#include <stdio.h>
#include <string.h>
char convert(char ch){
const char *lower_case = "abcdefghijklmnopqrstuvwxyz";
const char *upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *p;
if ((p = strchr(lower_case, ch)) != NULL)
return *(upper_case+(p-lower_case));
else if ((p = strchr(upper_case, ch)) != NULL)
return *(lower_case+(p-upper_case));
else
return ch;
}
int main(){
char ch;
printf("letter : ");
ch = getc(stdin);
printf("output : %c\n", convert(ch));
return 0;
}
Enter the array of 20 strings. Make program that prints out strings which have more consonants than vowels and in which letter 'r' is repeated at least 3 times.
I belive that the problem is in my if loops, but somehow i fail to understand why it does not work properly. It prints every string I enter.
This is the code i wrote:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char string[20][50];
int i, j;
int vowels=0;
int consonants=0;
int repeated_r=0;
printf("Enter the array of 20 strings:\n");
for(i=0;i<20;i++){
gets(string[i]);
}
for(i=0;i<20;i++){
for(j=0;j<50;j++){
if(string[i][j] == 'r'){
repeated_r++;
}
else if(string[i][j] == 'a' || string[i][j] == 'e' || string[i][j] == 'i' || string[i][j] == 'o' || string[i][j] == 'u'){
vowels++;
}
else{
consonants++;
}
}
if(consonants>vowels && repeated_r>=3){
fflush(stdin);
puts(string[i]);
}
}
return 0;
}
You need to reset the counters after processing each string.
And don't use gets use fgets instead.
for(i=0;i<20;i++){
for(j=0;j<50;j++){
if(string[i][j] == 'r'){
repeated_r++;
}
else if(string[i][j] == 'a' || string[i][j] == 'e' || string[i][j] == 'i' || string[i][j] == 'o' || string[i][j] == 'u'){
vowels++;
}
else{
consonants++;
}
}
if(consonants>vowels && repeated_r>3){
fflush(stdin);
puts(string[i]);
}
//Reset the counters
consonants =0;
vowels =0;
repeated_r =0;
}
}
Also note that in your current code r is not considered as consonant.
You are not resetting the initial values of the variables in the outer loop
int vowels=0;
int consonants=0;
int repeated_r=0;
Also the condition in the inner loop
for(j=0;j<50;j++){
^^^^
is not correct because in this case there is an access to memory beyond stored strings in the array.
The letter 'r' is not counted as a consonant.
Take into account that the function gets is not a standard C function that is it is not supported by the C Standard any more.
And this call
fflush(stdin);
has undefined behavior.
I can suggest the following solution as shown in the demonstrative program below.
#include <stdio.h>
#include <string.h>
int main( void )
{
enum { M = 3, N = 50 };
char s[M][N];
for ( size_t i = 0; i < M; i++ )
{
fgets( s[i], N, stdin );
s[i][strcspn( s[i], "\n" )] = '\0';
}
const char *vowels = "aeiou";
const char r = 'r';
for ( size_t i = 0; i < M; i++ )
{
size_t repeated_r = 0;
size_t vowels_count = 0;
size_t n = strlen( s[i] );
for ( size_t j = 0; j < n; j++ )
{
repeated_r += s[i][j] == r;
vowels_count += strchr( vowels, s[i][j] ) != NULL;
}
if ( repeated_r >= 3 && vowels_count < n - vowels_count )
{
puts( s[i] );
}
}
return 0;
}
If to enter the following strings
Hello World
errors
photosynthesis_bro
then the program output might look like
errors
there is one more problem in your code, ypu're using gets. It'll also include white spaces so say if your string is "_ _ rrrbaeeeeiou _ ". It will print this string but actually this string should not have been printed.
Note that "" means a blank space.
According to your code, "_" will be counted in consonants and even though there are 4 consonants in your string(3 r and 1 b) and 8 vowels, it will print this string as output since the blank spaces will be counted as consonants.
Also in your code r is not counted as consonant
For my assignment I need to modify the following program. I can not use strings.h.
int main(void)
{
int c, countSpaces = 0;
printf("Type sentence:\n");
do
{
c = getchar();
if (c == ' ')
countSpaces = countSpaces + 1;
}
while (c != '\n');
printf("Sentence contains %d Spaces.\n", countSpaces);
return 0;
}
I tried using
if (c != EOF)
countSpaces = countSpaces + 1;
}
while (c != '\n');
printf("Sentence contains %d Spaces.\n", countSpaces - 1);
but that seems like a hacky and unelegant way to do this.
Can anyone help and/or explain to me how to do this better?
Thanks in advance
The code I posted counts the spaces in a sentence, I want to modify it to count all the characters in the input sentence. – fbN 21 secs ago
Have another counter outside the if condition.
#include <stdio.h>
int main(void)
{
int c;
int countSpaces = 0;
int countChars = 0;
puts("Type sentence:");
do {
c = getchar();
countChars += 1;
if (c == ' ') {
countSpaces += 1;
}
} while (c != '\n');
printf("Sentence contains %d spaces and %d characters.\n", countSpaces, countChars);
return 0;
}
Two notes. foo += 1 is shorthand for foo = foo + 1 without the precendence complexities of foo++.
Blockless if or while is playing with fire. Eventually you'll accidentally write this.
if( condition )
do something
whoops this is not in the condition but it sure looks like it is!
Always use the block form.
$ ./test
Type sentence:
foo bar baz
Sentence contains 2 spaces and 12 characters.
Note this says 12 because it's including the newline. That's because it's checking what c is after it's already been counted. You can fix this by checking c as its read. This is a fairly normal "read and check" C loop idiom.
// Note, the parenthesis around `c = getchar()` are important.
while( (c = getchar()) != '\n' ) {
countChars++;
if (c == ' ') {
countSpaces++;
}
}
$ ./test
Type sentence:
foo bar baz
Sentence contains 2 spaces and 11 characters.
I always prefer to use fgets() when reading a line from the console (stdin):
#include <stdio.h>
int main(void)
{
int i;
int length = 0;
char buffer[1024];
printf( "Enter some text> " );
fgets( buffer, sizeof(buffer), stdin );
// If the user inputs > 1024 letters, buffer will not be \n terminated
for ( i=0; buffer[i] != '\n' && buffer[i] != '\0'; i++ )
{
length += 1;
}
printf( "length: %d\n", length );
return 0;
}
I make this code that count length of the string given It's like strlen function.
and I used just scanf and it works perfectly even with spaces.
#include <stdio.h>
int main()
{
char *str = calloc(sizeof(char),50);
int i = 0, count = 0;
printf("Type sentence:\n");
scanf("%[^\n]",str);
while (str[i++] != '\0')
count++; //length of the string
printf("%d",count);
return 0;
}
and if you want just to count the characters in the string given use this code below:
#include <stdio.h>
int main()
{
char *str = calloc(sizeof(char),50);
int count = 0;
printf("Type sentence:\n");
scanf("%[^\n]",str);
for (int i = 0; str[i] != '\0'; i++)
if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z'))
count++;
printf("Sentence contains %d characters.\n",count);
return 0;
}
the output :
Type sentence:
hello world
Sentence contains 10 characters.
you can just calculate the result like this
int main(void)
{
int c, countSpaces = 0;
printf("Type sentence:\n");
do
{
c = getchar();
if (c == ' ')
countSpaces++;
}
while (c != '\n');
int countChar = c - countSpaces - 1 ; // -1 new line
printf("Sentence contains %d Spaces.\n", countSpaces);
printf("Sentence contains %d chars.\n", countChar);
return 0;
}
I wrote this simple code to check if a string is letters and spaces only
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
#define N 100
int checkString(char str1[]);
void main()
{
char str1[N];
scanf("%s", str1);
printf("%d",checkString(str1));
getch();
}
int checkString(char str1[])
{
int i, x=0, p;
p=strlen(str1);
for (i = 0; i < p ; i++)
{
if ((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= 'A' && str1[i] <= 'Z') || (str1[i] == ' '))
{
continue;
}
else{ return 0; }
}
return 1;
}
This works fine when I type something like :
hello asds //returns 1
hello1010 sasd // return 0
but if I type anything after space it returns 1, like this :
hello 1220 //returns 1
blabla 11sdws // returns 1
Can someone please tell me why?
The function can be written more simpler and correctly if to use standard C functions isalpha and isblank declared in header <ctype.h> For example
#include <ctype.h>
//...
int checkString( const char s[] )
{
unsigned char c;
while ( ( c = *s ) && ( isalpha( c ) || isblank( c ) ) ) ++s;
return *s == '\0';
}
If you want to check whether a string contains white spaces then instead of function isblank you should use function isspace.
Take into account that it is not a good idea to use statement continue in such simple loops. It is better to rewrite the loop without the continue statement.
And instead of function scanf it is better to use function fgets if you want to enter a sentence The function allows to enter several words as one string until the Enter will be pressed.
For example
fgets( str1, sizeof( str1 ), stdin );
Take into account that the function includes the new line character. So after entering a string you should remove this character. For example
size_t n = strlen( str1 );
if ( n != 0 && str1[n-1] == '\n' ) str1[n-1] = '\0';
You forgot about the numbers
int checkString(char str1[]) {
int i, x=0, p;
p=strlen(str1);
for (i = 0; i < p ; i++)
if ((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= 'A' && str1[i] <= 'Z') || (str1[i] == ' ') || (str1[i] >= '0' && str1[i] <= '9')) {
continue;
} else return 0;
return 1;
}
Or better
#include <ctype.h>
...
int checkString(char str1[]) {
int i, x=0, p;
p=strlen(str1);
for (i = 0; i < p ; i++)
if (isalnum(str1[i]) || (str1[i] == ' '))
continue;
else return 0;
return 1;
}
This is happening because you are taking input with scanf(%s,&str). In this way of input only characters before space \n or other whitespace characters are stored. So your when you enter space the input is stored only upto space.
eg, you input helloo 1234
Your str stores only helloo and 1234 remains in buffer. Try using getchar().
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
#define N 100
int checkString(char str1[]);
void main()
{
char str1[N];
int i=0;
while(1)
{
str1[i++]=getchar();
if(str1[i-1]=='\n') break;
}
printf("%d",checkString(str1));
getch();
}
int checkString(char str1[])
{
int i, x=0, p;
p=strlen(str1);
for (i = 0; i < p ; i++)
{
if ((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= 'A' && str1[i] <= 'Z') || (str1[i] == ' '))
{
continue;
}
else{ return 0; }
}
return 1;
}
When you use scanf("%s",str1);,you input hello 112,what str1 gets is hello.So you can use fgets(str1,N,stdin); to get the string.I think it will work.
There is a problem with your input String
scanf() which will take your input up to space only as it is whitespace
So when you input as hello 1234 actual input it is checking is hello . Check this by printing what you are taking input (that is print str1). Then you will come to know mistake in this code.
You can use gets or fgets to solve the problem.
if you print back the string you just scanf()ed you will notice that it only gets the first portion of all inputs. i.e. anything after the white space including the white space is ignored.
you could use getch() (windows) or getchar() (linux) to get every char input and terminate when you have a "\n" (newline)
source: http://www.cplusplus.com/reference/cstdio/scanf/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define N 100
int checkString(char str1[]);
void main()
{
int i = 0;
int c;
char str1[N];
memset(str1, 0, sizeof(str1));
do {
c = getchar();
str1[i++] = c;
} while ((c != '\n') && (i < (N - 1))); // (i < N - 1) reserves one place for null char
// last char is '\n' - remove it.
str1[i-1] = 0;
printf("Result: %s\n", checkString(str1) ? "letters and/or spaces only" : "other characters other than spaces and/or letters present");
}
// expects a null terminated string
int checkString(char str1[])
{
char* p = str1;
while (*p) {
if (!isalpha(*p) && !isspace(*p)) {
return 0;
}
p++;
}
return 1;
}