length of string in c language - c

i wrote this code:
printf("enter a string: ");
scanf("%s",C); // C= "Hello world this is a string"
printf("%d\n",strlen(C));
temp=com0(C);
this code shows that the length of the string is 5 which also mean that is the length of the first word only
i have to get the full length
but that's not the point the important thing is i have to pass the whole string to the function
which also print the length of the first word only and it should print the whole length instead
this is the code of the function:
bool com0(char k[]){
printf("%d\n",strlen(k));
if(k[0]>='a' && k[0] <= 'z'){
return com1(nextchar(k+1));
}
else{
return false;
}
}
it prints 5 also !
and this the result of execution:

using fgets instead of scanf fixed the problem!
printf("enter a string: ");
fgets(C,sizeof(C),stdin);
C[strcspn(C,"\n")] = 0; // C = "Hello world this is a string"
printf("%d\n",strlen(C)); // print 28
temp=com0(C);

Related

String array for palindrome is adding some extra characters like ⌂ [duplicate]

This question already has answers here:
How should character arrays be used as strings?
(4 answers)
Closed last year.
I wanted to do a palindrome but when I do the code below:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char string[100];
int comparison;
char again;
printf("This program will determine whether a word is a Palindrome or not.\n");
do
{
start:
int c;
printf("Enter the word: \n");
scanf("%s", string);
int length = strlen(string);
char palindrome[length];
for(int i = 0; i<length; i++)
{
palindrome[i] = string[length-1-i];
printf("%c\n", palindrome[i]);
int validation = isalpha(palindrome[i]);
if(validation==0)
{
printf("Invalid Input! The input must be letters.\n");
goto jump;
}
}
printf("%s\n", palindrome);
comparison = strcmp(string,palindrome);
if(comparison == 0 )
{
printf("The word %s is a palindrome.\n", palindrome);
}
else
{
printf("The word %s is not a palindrome.\n", palindrome);
}
printf("Do you want to restart the code? Input Y to restart, otherwise any key to terminate \n" );
scanf("%s", &again);
while ( (c = getchar()) != '\n' && c != EOF ) { }
}
while((again == 'Y') || (again == 'y'));//this will then loop back the code if again is Y, otherwise continues to the next chunk
printf("Code terminated");
return 0;
jump://If an invalid input will be placed, the code will jump here
printf("Do you want to restart the program? Input Y to restart, otherwise any key to terminate \n" );
char again2;
scanf(" %c", &again2);
if((again2 == 'Y') || (again2 == 'y'))
{
goto start;//jumpts to the start on the top
}
printf("Code terminated");
return 0;
}
When I input racecar, the code will execute correctly.
But when I input the word civic I get this:
civic
c
i
v
i
c
civic⌂
The word civic⌂ is not a palindrome.
Why is there an additional character ⌂?Thank you
Add null terminator ('\0') at the end of the string palindrome.
For example:
palindrome[length] = '\0';
Add the above line after copying all the character from string array to palindrome array.
If your string is not terminated with \0, it might still print the expected output because following your string is a non-printable character in your memory. This is a bug though, since it might blow up when you might not expect it. Always terminate a string with '\0'.
Note: As you're adding length number of character in the palindrome array, declare the size of palindrome array length +1 ( i.e. char palindrome[length + 1];)

C: Trying to remove newline character from end of string

I'm trying to write a program that deletes the last newline from user input, ie the one generated when the user hits enter after having typed in a string.
void func4()
{
char *string = malloc(sizeof(*string)*256); //Declare size of the string
printf("please enter a long string: ");
fgets(string, 256, stdin); //Get user input for string (Sahand)
printf("You entered: %s", string); //Prints the string
for(int i=0; i<256; i++) //In this loop I attempt to remove the newline generated when clicking enter
//when inputting the string earlier.
{
if((string[i] = '\n')) //If the current element is a newline character.
{
printf("Entered if statement. string[i] = %c and i = %d\n",string[i], i);
string[i] = 0;
break;
}
}
printf("%c",string[0]); //Printing to see what we have as the first position. This generates no output...
for(int i=0;i<sizeof(string);i++) //Printing the whole string. This generates the whole string except the first char...
{
printf("%c",string[i]);
}
printf("The string without newline character: %s", string); //And this generates nothing!
}
But it doesn't behave as I thought it would. Here's the output:
please enter a long string: Sahand
You entered: Sahand
Entered if statement. string[i] =
and i = 0
ahand
The string without newline character:
Program ended with exit code: 0
Questions:
Why does the program seem to match the '\n' with the first character 'S'?
Why does the last line printf("The string without newline character: %s", string); generate no output at all when I haven't deleted anything from the string?
How can I make this program do what I intend it to do?
The condition (string[i] = '\n') will always return true. It should be (string[i] == '\n').
if((string[i] = '\n'))
this line may be wrong, you are assign value to string[i], not compare it.
if((string[i] == '\n'))

Why does fgets function in the program below (see detail) interprets the length of string by one extra character?

Here is the source code with gets function:
//Finding length of a string//
#include<stdio.h>
#include<conio.h>
int main()
{
//Finding length by user written code//
int i=0;
char ar[200];
printf("So enter your string here: ");
gets(ar);
while(ar[i]!='\0')
i++;
printf("The length of your string is: %d",i);
getch();
return 0;
}
Here are the input and output:
So enter your string here: Hello World
The length of your string is: 11
But if the gets function is replaced by fgets function, that is if the code is written as:
//Finding length of a string//
#include<stdio.h>
#include<conio.h>
int main()
{
//Finding length by user written code//
int i=0;
char ar[200];
printf("So enter your string here: ");
fgets(ar,200,stdin);
while(ar[i]!='\0')
i++;
printf("The length of your string is: %d",i);
getch();
return 0;
}
Then input and output become:
So enter your string here: Hello World
The length of your string is: 12
So, why is fgets function giving the length by one extra character?
It is because fgets stores a \n character before adding the null-terminating \0.
from cppreference fgets
... Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character.
and from cppreference gets
The newline character, if found, is discarded and does not count toward the number of characters written to the buffer.

Substring in C (what will happen to the remaining in array)

I have given a task to generate a sub string for the given input in C. The code as follows.
#include<stdio.h>
int main(){
char a[1000];
char *sub;
int startFrom = 0;
int endAt = 0;
printf("Enter the String: ");
scanf("%s", a);
printf("Start From? ");
scanf("%d", &startFrom);
printf("End At? ");
scanf("%d", &endAt);
sub = &a[startFrom];
a[endAt] = '\0';
printf("%s\n", sub);
return 0;
}
The code however works fine, but what will happen to the rest of the characters in the array?
The rest of the array remains the same; it's just that you changed one of the characters in the array to null('\0'). So if you try to access any other character after (or before) the a[endAt] character, you would be able to do so.
Check it out Your code with some extra at Ideone.com.
However as you can see, when you try to print the original array, it would be printed only till the first '\0' character.

How to clear input buffer after fgets overflow?

I'm facing a little problem with fgets when the input string exceeds its predefined limit.
Taking the example below:
for(index = 0; index < max; index++)
{printf(" Enter the %d string : ",index+1)
if(fgets(input,MAXLEN,stdin))
{
printf(" The string and size of the string is %s and %d \n",input,strlen(input) + 1);
removeNewLine(input);
if(strcmp(input,"end") != 0)
{ //Do something with input
}
}
Now when I exceed the length MAXLEN and enter a string, I know that the input will append a '\0' at MAXLEN -1 and that would be it. The problem happens when I try to enter the 2nd string which is not asked for i.e
Output :
Enter the first string : Aaaaaaaaaaaaaaaaaaaa //Exceeds limit
Enter the second string : Enter the third string : ....Waits input
So, I thought I should clear the buffer the standard way as in C. It waits until I enter
return
two times, The first time it being appended to the string and the next time,expecting more input with another return.
1. Is there any method by which I can clear the buffer without entering the extra return?
2. How do I implement error handling for the same? Because the fgets return value will be Non-null and strlen(input) gives me the accepted size of the string by fgets, what should be done?
Thanks a lot
If I understood correctly, looks like you want to avoid twice enter press, when entered input is within range.
A work around would be
for(index = 0; index < max; index++)
{
printf(" Enter the %d th string :",index);
// if (strlen(input) >=MAXLEN )
if(fgets(input,MAXLEN,stdin))
{
removeNewLine(input);
if(strcmp(input,"end") != 0)
// Do something with input
;
}
if (strlen(input) == MAXLEN-1 )
while((ch = getchar())!='\n' && ch != EOF );
}
With a limitation that it will again ask for two times enter when entered characters are exactly MAXLEN-2.
Or else you can simply form your input using character by character input.
while ((c=getchar()) != '\n' && c != EOF)
;
or:
scanf("%*[^\n]%*c");

Resources