Printing a string of names in different lines - arrays

I have recently started learning C, and I made this small piece of code, but it's not really working the way I wanted:
#include <stdio.h>
#include <string.h>
int main()
{
int i;
char a[] = "Bill Sarah Alice";
for (i = 0; a[i] != '\0'; i++)
{
if (a[i] != '\t' || a[i] != ' ')
{
printf("%c", a[i]);
}
putchar('\n');
}
return 0;
}
I wanted to print one name per line, but instead its printing one character per line. Can someone tell how should I fix it so it will work?

if(a[i] != '\t' || a[i] != ' '){
Every character is not tab or not space. So this if will be passed by every single character. You then output a newline after every single character. So this code is equivalent to this:
for(i=0; a[i] != '\0'; i++){
printf("%c", a[i]);
putchar('\n');
}
If you want to print each name on a line, you need to do something more like this:
for(i=0; a[i] != '\0'; i++){
if(a[i] == '\t' || a[i] == ' ')
putchar('\n');
else
printf("%c", a[i]);
}
putchar('\n');

Alternatively to other answers you can use isspace to detect spaces or tabs:
#include <ctype.h> // for isspace()
#include <stdio.h>
int main()
{
int i;
char a[] = "Bill Sarah Alice";
for (i = 0; a[i] != '\0'; i++)
{
if (!isspace(a[i])) // if it's not a space
{
printf("%c", a[i]); // print character
}
else
putchar('\n'); // if it is print a newline
}
}
Output:
Bill
Sarah
Alice

There are two issues in your code. First, the newline character will be printed on every run through the for loop; to fix this, put the putchar('\n'); line into an else block.
Second, your test condition is wrong and can never be false: the character cannot be both a tab and a space, so one of the != tests will always be true; to fix this, change the || to a &&.
int main()
{
int i;
char a[] = "Bill Sarah Alice";
for (i = 0; a[i] != '\0'; i++) {
if (a[i] != '\t' && a[i] != ' ') {
printf("%c", a[i]);
}
else {
putchar('\n');
}
}
return 0;
}

Within the for loop an output of the new line character '\n' is executed after printing each character in the string that is not equal to '\t' or to ' '.
if(a[i] != '\t' || a[i] != ' '){
printf("%c", a[i]);
}
putchar('\n');
Moreover the condition in the if statement shall be written at least like
if(a[i] != '\t' && a[i] != ' '){
^^^^
You need to output the new line character after a whole name is outputted. So if you are outputting a name character by character then you need one more inner loop.
Also the header <string.h> is redundant because neither declaration from the header is used in your program. So you may remove the directive
#include <string.h>
The algorithm can look the following way as it is shown in the demonstrative program below. It is implemented as a separate function.
#include <stdio.h>
void print_names( const char *s )
{
while ( *s != '\0' )
{
while ( *s == ' ' || *s == '\t' ) ++s;
while ( *s && *s != ' ' && *s != '\t' ) putchar( *s++ );
putchar( '\n' );
}
}
int main(void)
{
char a[] = "Bill Sarah Alice";
print_names( a );
return 0;
}
The program output is
Bill
Sarah
Alice
If to include the header <ctype.h>
#include <ctype.h>
then the function can be rewritten using the standard C function isblank that itself does the check whether a character is equal to the space character or to the tab character.
#include <stdio.h>
#include <ctype.h>
void print_names( const char *s )
{
while ( *s != '\0' )
{
while ( isblank( ( unsigned char )*s ) ) ++s;
while ( *s && !isblank( ( unsigned char )*s ) ) putchar( *s++ );
putchar( '\n' );
}
}
//...

What you want, is the function strtok(3).
strtok uses a delimiter string to return parts of the string. By using " " as a delimiter, you can easily extract the names. For how to use the function read the man page I linked above. Or read this article.
You can print the names one at a time using the following code
#include <stdio.h>
#include <string.h>
int main
(int argc, char *argv[], char *envp[])
{
char a[] = "Bill Sarah Alice";
char *tok = strtok (a, " ");
while (tok) {
puts (tok);
tok = strtok (NULL, " ");
}
return 0;
}

Related

Make first letter of every word capital after removing vowels

My code works to delete any vowels and prints the first letter of the word as a capital letter.
How can I get my expected output to work?
If the value is " I am Iron Man" (with a leading space), it works and prints "M Rn Mn".
However, without the space at the beginning of the string, my output is "m Rn Mn" but
the expected output is "M Rn Mn".
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char str[] = "I am Iron Man";
int i, j, len = 0;
len = strlen(str);
// Accepting input.
for (i = 0; i < len; i++) {
// Check vowels.
if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' ||
str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U') {
// delete vowel syntax
for (j = i; j < len; j++) {
// Store after removing vowels
str[j] = str[j + 1];
}
i--;
len--;
}
str[len + 1] = '\0';
}
for(i=0; str[i]!='\0'; i++)
{
//check first character is lowercase alphabet
if(i==0)
{
if((str[i]>='a' && str[i]<='z'))
str[i]=str[i]-32; //subtract 32 to make it capital
continue; //continue to the loop
}
if(str[i]==' ')//check space
{
//if space is found, check next character
++i;
//check letter if lowercase
if(str[i]>='a' && str[i]<='z')
{
str[i]=str[i]-32; //subtract 32 to make it capital
continue; //continue to the loop
}
}
}
printf("%s", str);
return 0;
}
Your problem lies with excessive use of the continue statement in the second for loop. The second continue is just plain pointless, as control reaches the end of the loop, anyway, after the point where you have that.
But the first continue is actually causing the fault: after removal of the vowels, the first character in the modified string will be a space – so, the first if block inside the second loop will be entered, and that will skip the check for a lowercase letter following the space.
Removing those continue statement will fix your code.
Also, note that you can use the islower and toupper functiosn to check for lowercase letters and convert to uppercase:
#include <stdio.h>
#include <string.h>
#include <ctype.h> // For islower and toupper
int main()
{
char str[] = "I am Iron Man";
size_t i, j, len = 0;
len = strlen(str);
// Accepting input.
for (i = 0; i < len; i++)
{
// Check vowels.
if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' ||
str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U') {
// delete vowel syntax
for (j = i; j < len; j++)
{
// Store after removing vowels
str[j] = str[j + 1];
}
i--;
len--;
}
str[len + 1] = '\0';
}
for (i = 0; str[i] != '\0'; i++)
{
//check first character is lowercase alphabet
if (i == 0)
{
if (islower(str[i])) {
str[i] = toupper(str[i]);
}
// A "continue" here is wrong ... it will skip the following check for a lowercase letter
}
if (str[i] == ' ') //check space
{
//if space is found, check next character
++i;
//check letter if lowercase
if (islower(str[i]))
{
str[i] = toupper(str[i]);
// No need for a "continue" here ... we're already at the end of the loop
}
}
}
printf("%s\n", str);
return 0;
}
I have another solution for you, that may be a bit easier to comprehend:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char str[] = "I am Iron Man";
char *in;
char *out;
int up = 1; // very simple state, if "up" then next character should be made upper
for (in = str, out = str; *in; in++) {
if (strchr("aeiouAEIOU", *in) != NULL) {
// do nothing
} else if (*in == ' ') {
*out++ = *in;
up = 1; // we see a space, so next letter should be upper
} else if (up) {
*out++ = toupper(*in);
up = 0; // we see a letter (or other character), ignore case
} else {
*out++ = *in;
}
}
*out = '\0';
printf("%s\n", str);
}
Or, if you don't like/understand the pointer syntax:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char str[] = "I am Iron Man";
int i;
int o;
int up = 1; // very simple state, if "up" then next character should be made upper
for (i = 0, o = 0; str[i]; i++) {
if (strchr("aeiouAEIOU", str[i]) != NULL) {
// do nothing
} else if (str[i] == ' ') {
str[o++] = str[i];
up = 1; // we see a space, so next letter should be upper
} else if (up) {
str[o++] = toupper(str[i]);
up = 0; // we see a letter (or other character), ignore case
} else {
str[o++] = str[i];
}
}
str[o] = '\0';
printf("%s\n", str);
}
In both cases, a very simple state is used. For more complex conditions, you should learn about state machines. In this case, the up state indicates that the next letter should be capitalised.
Note that if you want to remove leading spaces, after "removing" the vowels, you need to modify the logic a bit:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char str[] = "I am Iron Man";
char *in = str; // we initialize in and out here already
char *out = str;
int up = 1; // very simple state, if "up" then next chacter should be made upper
// we skip leading vowels AND spaces, this is a special case
while (*in && (strchr("aeiouAEIOU ", *in) != NULL)) {
in++;
}
// now we are at the first character that is not a vowel or space
for ( ; *in; in++) {
if (strchr("aeiouAEIOU", *in) != NULL) {
// do nothing
} else if (*in == ' ') {
*out++ = *in;
up = 1; // we see a space, so next letter should be upper
} else if (up) {
*out++ = toupper(*in);
up = 0; // we see a letter (or other character), ignore case
} else {
*out++ = *in;
}
}
*out = '\0';
printf("%s\n", str);
}
Well now you have a few examples to study that take a bit of a different approach. See if you understand the logic, and try to make it so that other characters like e.g. ( and ) also delimit words.
One of the problems is that you've got too much code. It iterates through the entire array once to strip out vowels, then again to adjust the case of the first letter of each word. Imagine this is processing data that is measured in Gb. A second pass is unnecessary.
(And, there are standard library functions like isalpha() and toupper() that you should use. Don't write code with "magic numbers".)
It's worth studying a program's 'flow control', without resorting to arbitrary 'continue' statements to affect that flow.
It's also worth starting from scratch with a minimal block of code in main(), then developing your algorithm in a function (or several). Avoid the tendency to have one long, linear program all inside main(). If you can put functionality into 'compartments', each can be developed and tested and forgotten about as the program grows more complex.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
// A single pass "compacts" the data (no vowels) while also using some single operations
//tracking changing from one word to the next (first letter to uppercase.)
char *func( char *str ) {
for ( int d = 0, s = 0, up = 0; (str[d] = str[s]) != '\0'; s++)
if( !strchr( " aeiouAEIOU" + !!up, str[d] ) ) {
if( str[d] == ' ' )
up = 1;
else if( up++ < 2 )
up++, str[d] = (char)toupper( (unsigned char)str[d] );
d++; // 'd'estination idx only increments here!
}
return str;
}
int main(void) {
// sample test strings
char *strs[] = {
"I am Iron Man",
" I am Iron Man ",
"Iron Man am I",
" Iron Man am I",
"The man of steel",
" The man of steel",
};
for( size_t i = 0; i < sizeof strs/sizeof strs[0]; i++ )
puts( func( strs[i] ) );
return 0;
}
M Rn Mn
M Rn Mn
Rn Mn M
Rn Mn M
Th Mn F Stl
Th Mn F Stl

Keep getting gibberish output when trying to print an array in C

I am trying to write a program that reverses words in a sentence, the code is able to do that but also prints gibberish in between. (see below code for sample)
#include <stdio.h>
#define MAX_VALUE 50
int main(){
char c[MAX_VALUE],
b[MAX_VALUE];
int i = 0, j = 0;
while ((c[i] = getchar()) != '\n'){
i++;
}
for(i = MAX_VALUE; i >= 0; i--){
if (c[i] == ' '){
for(j = i+1; j < MAX_VALUE; j++){
if (c[j] != ' '){
printf("%c", c[j]);
}
else{
break;
}
}
printf(" ");
}
}
while (c[i] != ' '){
printf("%c", c[i]);
i++;
}
}
Loop goes backwards when it detects a space it prints the word until it finds another space then goes backwards again from where it left off last
The input and output expected:
input: test a is this
output: this is a test
What I get:
input: test a is this
output:
this
`����l�,+�D �=� is a test
This for loop
while ((c[i] = getchar()) != '\n'){
i++;
}
can write outside the array c and store the new line character '\n' in the array.
And this output consisting from two lines
this
`����l�,+�D �=� is a test
demonstrates that the new line character was stored in the array.
Also you forgot to append the entered sequence of characters with the zero terminating character '\0' to form a string.
You could write the while loop the following way
int ch;
while ( i < MAX_VALUE - 1 && ( ch = getchar() ) != '\n' && ch != EOF ){
c[i++] = ch;
}
c[i] = '\0';
Or if you want store the entered sequence without the terminating zero character '\0' then the loop can look like
int ch;
while ( i < MAX_VALUE && ( ch = getchar() ) != '\n' && ch != EOF ){
c[i++] = ch;
}
In this case the variable i will contain the number of entered symbols in the array and you should use its value instead of the value MAX_VALUE in the following loops.
This outer for loop
for(i = MAX_VALUE; i >= 0; i--){
is incorrect because the user can enter a sequence of symbols that contains less than MAX_VALUE symbols. You should either use standard string function strlen (if you appended the sequence with the terminating zero character '\0') to determine the length of the string stored in the array or the value of the variable i as mentioned above that denotes the number of entered symbols.
And it is not enough to check this condition
if (c[i] == ' '){
because the leading spaces can be absent in the entered string. So you need to check also whether i is equal to 0. Otherwise the output can be incorrect if the sequence contains for example only one word.
The inner for loop
for(j = i+1; j < MAX_VALUE; j++){
again is incorrect by the same reason of using MAX_VALUE in the condition.
Pay attention to that the array b
char c[MAX_VALUE],
b[MAX_VALUE];
is not used in your program.
Using your approach I can suggest the following solution to output words of a string in the reverse order shown in the demonstrative program below.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main( void )
{
const char *s = "test a is this";
for( size_t i = strlen( s ); i != 0; )
{
while ( i != 0 && isblank( ( unsigned char )s[i-1]) )
{
putchar( s[--i] );
}
size_t j = i;
while ( j != 0 && !isblank( ( unsigned char )s[j-1]) )
{
--j;
}
if ( j != i )
{
size_t last = i;
i = j;
while ( j != last )
{
putchar( s[j++] );
}
}
}
putchar( '\n' );
}
The program output is
this is a test
The code uses two arrays and two 'counters', and fiddles around with individual characters one-at-a-time. It's easy to get lost and use an upper bound that is outside the array size.
Simplify! This "reversal" is an excellent example of when recursion should be the go-to method of solving the problem.
#include <stdio.h>
#include <string.h>
void output( char *p ) {
if( (p = strtok( p, " " )) == NULL ) return;
output( NULL );
printf( "%s ", p );
}
int main() {
char str[] = "The quick brown fox jumps over the dogs";
output( str );
return 0;
}
dogs the over jumps fox brown quick The
Some purists may want an entire buffer to be assembled before printing. This resulting string includes an invisible SP at the end that could be lopped off if desired.
#include <stdio.h>
#include <string.h>
char *revWords( char *dst, char *p ) {
if( (p = strtok( p, " " )) == NULL ) return NULL;
revWords( dst, NULL );
return strcat( strcat( dst, p ), " " );
}
int main() {
char str[] = "The quick brown fox jumps over the dogs";
char buf[sizeof str + 1 + 1] = { 0 }; // important to initialise
puts( revWords( buf, str ) );
return 0;
}
For an alternative, here's a version without recursion. It requires, like above, a mutable buffer holding the string.
#include <stdio.h>
#include <ctype.h>
int main() {
char str[] = " The quick brown fox jumps over the dogs ";
int i = 0;
// note: 1 string buffer, 1 index variable
for( i = 0; str[i]; i++ ) ; // loop
while( i >= 0 ) {
while( i >= 0 && !isalnum( str[ i ] ) ) str[i--] = '\0';
while( i >= 0 && isalnum( str[ i ] ) ) i--;
printf( "%s ", str + i + 1 );
}
puts( "" );
return 0;
}

How to have a function output a string, not just the first word

I'm writing a function to capitalize every lowercase character in a string. It takes a string from the user and that is the input to the function. My program works if the user doesn't enter spaces, but when there is a space in the string, the function ends.
#include <stdio.h>
char *uppercase(char *c) {
int i = 0;
while (c[i] != '\0') {
if (123 > c[i] && c[i] > 96)
c[i] = c[i] - 'a' + 'A';
i++;
}
return c;
}
int main() {
char input[100];
printf("Enter the phrase: ");
scanf("%s", input);
printf("%s", uppercase(input));
return 0;
}
Examples:
Input: test test
Output: TEST
Input: Hello
Output: HELLO
Input: How are you
Output: HOW
I think it has to do with the while statement? Thanks for the help.
The problem is not in the while statement, but rather due to the scanf() format: %s reads a single word from the input, leaving the rest of the line in the stdin buffer. Note also that typing a word with more than 99 characters will cause undefined behavior because scanf() will write beyond the end of the input array. Using %99s would prevent this problem, but not solve your issue.
You should use fgets() to read a full line of input from stdin.
Furthermore, instead of using hard coded ASCII values, you should use character constants such as 'a' and 'z' or the functions from <ctype.h>.
Here is a modified version using ASCII:
#include <stdio.h>
char *uppercase(char *s) {
int i = 0;
while (s[i] != '\0') {
if (s[i] >= 'a' && s[i] <= 'z')
s[i] = s[i] - 'a' + 'A';
i++;
}
return s;
}
int main() {
char input[100];
printf("Enter the phrase: ");
if (fgets(input, sizeof input, stdin)) {
fputs(uppercase(input), stdout);
}
return 0;
}
Here is a more portable one using <ctype.h>:
#include <ctype.h>
#include <stdio.h>
char *uppercase(char *s) {
int i = 0;
unsigned char c;
while ((c = s[i]) != '\0') {
if (islower(c))
s[i] = toupper(c);
i++;
}
return s;
}
This can be further simplified as toupper() can be called for all byte values from 0 to UCHAR_MAX:
#include <ctype.h>
#include <stdio.h>
char *uppercase(char *s) {
for (size_t i = 0; s[i] != '\0'; i++) {
s[i] = toupper((unsigned char)c);
}
return s;
}
Either use
scanf ("%99[^\n]", input);
or
fgets( input, sizeof( input ), stdin );
Also it is a bad practice to use magic numbers like 123 or 96
if (123 > c[i] && c[i] > 96)
The code will be more readable if you will write at least
if ( 'a' <= c[i] && c[i] <= 'z' )
Also instead of the while loop it is better to use the for loop like
for ( char *p = c; *p; ++p )
{
if ( 'a' <= *p && *p <= 'z' )
{
*p = *p - 'a' + 'A';
}
}

a function produces an inifinite loop

I wrote the following function and when I run it , it produces an infinite loop and I dont understand why.
This function creates a dynamic array of dynamic strings. Every such string starts with a letter given, or with a capital letter which is compatible to the letter given:
void wordsStartWithLetter(char letter, char *str,char***newstr,int *numOfWords)
{
int i=0, count=0;
char *word;
char *delimiter = " ";
while (str[i] != '\0')
{
if (str[i]==letter ||str[i]==(letter-32 )) //if it founds the letter at the begining of the word, than run till the space//
{
while (str[i] != ' ' && str[i] != '\0' )
i++; //counting the number of words beginng with the letter given//
count++;
}
else
{
while (str[i] != ' ' && str[i] != '\0' )
i++;
}
}
*newstr = (char**)malloc (sizeof(char*)*count);
*numOfWords=count;
i=0;
word = strtok(str, delimiter); //we use strtok to separate each word from the origin string//
while(word!=NULL)
{
if (word[0]==letter ||word[0]==letter-32)
{
(*newstr)[i]=word; //insert the compatible words into the new 2D-string//
i++;
}
word = strtok(NULL, delimiter);
}
}
I call that function the by the following way:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#define SIZE 50
void Ex();
void wordsStartWithLetter(char letter, char *str,char***newstr,int *numOfWords) ;
void main()
{
Ex();
}
void Ex()
{
char ch;
char str[SIZE];
char **newstr;
int numOfWords,i;
printf("please enter a string: ");
_flushall();
gets(str);
printf("plese enter a letter: " );
_flushall();
ch=_getche();
wordsStartWithLetter(ch, str,&newstr,&numOfWords);
("the words of the origin string which start which %c :\n",ch);
for(i=0;i<numOfWords;i++)
printf("%s\n",newstr[i]);
for (i=0;i<numOfWords; i++)
free(newstr[i]);
free(newstr);
}
Consider this input string "a b" and assume the letter is c.
When i is 0 you enter the code below because str[0]is a which doesn't match the letter:
else
{
while (str[i] != ' ' && str[i] != '\0' )
i++; // Increment i from 0 to 1
}
In the above block, you increment i to 1 and then leave the block because str[1] is ' '
In the next main loop, you will again hit this code block:
else
{
while (str[i] != ' ' && str[i] != '\0' )
i++; // No increment, i.e. i stays at 1
}
but you will not increment i (as str[1] is a space). In other words - i remains at 1 and you have an infinite loop.
Maybe you can fix it by this:
else
{
while (str[i] != ' ' && str[i] != '\0' )
i++; // No increment, i.e. i stays at 1
// Add this line to remove the spaces
while (str[i] == ' ') i++;
}

Checking if string is only letters and spaces

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

Resources