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'))
Related
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];)
I am just running a code to find the length of a given string input by the user in C programming language. I used a loop condition to determine the length but statements inside loop executes when the condition is false also. The code I have tried in c is:
#include <stdio.h>
#define ArrayLength 50
int StringLengthCount();
int main() {
printf("Hello, World!\n");
/*Question: Find inserted string's length, without build in function*/
int c=StringLengthCount();
printf("Your inserted string's length is:%d",c);
return 0;
}
int StringLengthCount(){
printf("\n");
printf("Please enter a sentence to find its length of character:");
char array1[ArrayLength];
fgets(array1,ArrayLength,stdin);
printf("Your inserted string is:%s\n",array1);
int i=0;
int count=0;
while(array1[i]!='\0'){
count++;
printf("%d character is %c",count,array1[i]);
printf("\n");
i++;
}
printf("\n");
printf("Your inserted string's total character i.e string length is:%d",count);
}
I am expecting the result 2 for a sample string input "we", but it gives result 3.
The output result in CLion compiler is given below
enter image description here
Can you kindly tell me why it happens?
If by "statements inside loop executes when the condition is false also" you mean that you see an extra character every time you execute remember that also the line feed (LF alias \n) character that you use to enter your string is part of the acquired string.
So even the empty string has one character that is \n or 0x10.
Your check should be something like this:
while (array1[len] != '\0' && array1[len] != '\n' )
And you function, as suggested in the comments, should have a return and could use just one variable like this:
int StringLengthCount() {
printf("\n");
printf("Please enter a sentence to find its length of character:");
char array1[ArrayLength];
fgets(array1, ArrayLength, stdin);
printf("Your inserted string is:%s\n", array1);
int len = 0;
while (array1[len] != '\0' && array1[len] != '\n' ) {
printf("%d character is %c", len + 1, array1[len]);
printf("\n");
len++;
}
printf("\n");
printf("Your inserted string's total character i.e string length is:%d\n\n",
len);
return len;
}
The function fgets will also read the newline character, so you need to change the condition in the while-loop from str[i] != '\0' to str[i] != '\n'. I have also implemented the suggested changes by Devolus.
#include <stdio.h>
#include <stdlib.h>
#define LEN 50
void string_length();
int main(void)
{
string_length();
return EXIT_SUCCESS;
}
void string_length(void)
{
printf("Enter a string: ");
char str[LEN];
fgets(str, LEN - 1, stdin);
printf("Your entered string is: %s\n", str);
int i = 0;
while (str[i] != '\n') {
printf("The %d. character is '%c'.\n", i + 1, str[i]);
++i;
}
printf("\nThe string's length is %d.\n", i);
}
This question already has an answer here:
fgets is getting skipped
(1 answer)
Closed 4 years ago.
Been trying to remove a character but the call to fgets gets skipped/jumped over. On different computers it runs like it should but for some reason, it skips and basically jumps to the end of the program. Any ideas?
Several problems in your code but I do not see any reason of fgets() skipped or jumped over. The getchar() function reads the next character from stdin. Generally when we give input to the getchar() function, we enter the character and press ENTER key. This left the \n character in input stream which can be consumed by next input function called. But in your case you are not calling any other input function after getchar().
[Try calling getchar() above fgets() and give input as - enter a character followed by ENTER key. You will see the fgets() is skipped because it consumes the leftover \n character from input stream stdin.]
Problem 1:
Look at this statement:
str[j] = str + 1;
Since, the str is a char array, str[j] represents a character at location j and str + 1 is pointer. So, this assignment is incompatible because you are trying to assign a char * type to a char. It should be:
str[j] = str[j + 1];
Problem 2:
Your code is having a logical problem. It is unable to handle the scenario where the character to be removed occurs consecutively in the input string. Test your code for input like "Hello World" [character l is occurring consecutively]. Your program output will be [after fixing problem 1]:
Enter a sentence:
Hello World
This is the sentence: Hello World
Enter character to remove:
l
Sentence after removal: Helo Word <==== character l not removed
Your program is unable to handle this particular scenario because once it removes a character, in the next iteration it starts with next character.
Problem 3:
The strlen() return type is size_t and you are using char type to receive its return value. Instead, you should use size_t type.
The getchar() return type is int [because it returns the special value EOF when the end of the input stream is reached]. You are using char type variable to receive getchar() return value.
One more point (it is not a problem but you should be aware of it and take the precautionary measures):
From fgets() [emphasis mine]:
Reads at most count - 1 characters from the given file stream and stores them in the character array pointed to by str. Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character. If no errors occur, writes a null character at the position immediately after the last character written to str.
So, it is possible that your input buffer passed to fgets() can have new line character ('\n') in it. For e.g., if you give input Hello World followed by ENTER key than the input buffer str will have "Hello World\n" in it. In your case this will not cause any problem but few extra iteration of loop. You can remove the \n from str buffer like this:
fgets(str, 100, stdin);
str[strcspn(str, "\n")] = 0; // This will remove the trailing newline character from input buffer
Also, you should check the fgets() return. In case of failure, fgets() returns NULL.
Putting these altogether, you can do:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
size_t i, j, len;
int r;
printf("Enter a sentence: \n");
if (fgets(str, 100, stdin) == NULL) {
fprintf (stderr, ("fgets failed"));
return -1;
}
str[strcspn(str, "\n")] = 0;
printf("This is the sentence: %s\n", str);
printf("Enter character to remove: \n");
r = getchar();
/*If getchar returns EOF, no need to go through character removal logic*/
if (r != EOF) {
len = strlen(str);
i = 0;
while (str[i] != '\0') {
if (str[i] == (char)r) {
for (j = i; j < len; j++) {
str[j] = str[j+1];
}
len--;
}
else
i++;
}
}
printf("Sentence after removal: %s\n", str);
return 0;
}
Output:
# ./a.out
Enter a sentence:
Hello World
This is the sentence: Hello World
Enter character to remove:
l
Sentence after removal: Heo Word
# ./a.out
Enter a sentence:
zzzzz
This is the sentence: zzzzz
Enter character to remove:
z
Sentence after removal:
# ./a.out
Enter a sentence:
aazz
This is the sentence: aazz
Enter character to remove:
a
Sentence after removal: zz
Try changing r = getchar(); with scanf("%c\n", &r);.
Also, your loop has some bugs or inconsistencies:
You're assigning to str[j] the value of a pointer. Should be assigning to str[j] the value of str[j+1].
The end of the inner loop should be len-1 then.
j-- has no effect at all.
You should end your string with \0 after you're done, otherwise you'll print garbage (in my case it was a bunch of \ns).
Putting everything together:
for (i = 0; i < len; i++) {
if (str[i] == r) {
for (j = i; j < len-1; j++) {
str[j] = str[j+1];
}
len--;
}
}
str[len] = '\0';
printf("Sentence after removal: %s\n", str);
If you want to remove the \n at the end of the string after you read it, you can do
str[len] = '\0';
len--;
before the loop.
I am trying to run the following code but the program accepts only one string and displays the output immediately without waiting for the second string to be entered. The program is for 2 string concatenation. Here is the code :-
#include <stdio.h>
main()
{
int i, j, len=0;
char name[100], abc[100];
printf("\nPlease Enter String 1 =\t");
scanf("%[^\n]c",&name);
printf("\nPlease Enter String 2 =\t");
scanf("%[^\n]c",&abc);
for(i=0; name[i]!='\0'; i++)
len++;
for(j=0; abc[j]!='\0'; j++)
{
len++;
name[len]=abc[j];
}
printf("\nThe Concatenated String Is =\t");
puts(name);
}
Use fgets instead of scanf, also you were incrementing len at the wrong place:
#include <stdio.h>
#include <string.h>
int main() {
int len = 0;
char name[100], abc[100];
printf("\nPlease Enter String 1 =\t");
fgets(name, 100, stdin);
len = strlen(name) - 1;
name[len] = 0;
printf("\nPlease Enter String 2 =\t");
fgets(abc, 100, stdin);
abc[strlen(abc) - 1] = 0;
strcpy(name+len, abc);
printf("\nThe Concatenated String Is =\t");
puts(name);
return 0;
}
Use the following scanf instead:
scanf("%[^\n]",name);
.....
scanf(" %[^\n]",abc);
Please refer to this scanf() manual page for more detail of how to use scanf().
You have to throw away the newline character ('\n').
Try:
while(getchar() != '\n')
continue;
after each scanf
I would like to suggest you not to use scanf. Better to use fgets instead.
By the way the reason that your program accepts only one string and displays the output immediately without waiting for the second string to be entered is the \n character left behind by the first scanf after pressing the Enter key. To eat up this newline character you may use gatchar() after first scanf.
printf("\nPlease Enter String 1 =\t");
scanf("%[^\n]c",name);
getchar();
printf("\nPlease Enter String 2 =\t");
scanf("%[^\n]c",abc);
Other two mistakes are:
1. Wrong increment of len
for(i=0; name[i]!='\0'; i++)
len++;
for(j=0; abc[j]!='\0'; j++)
{
name[len++]=abc[j];
}
2. Reason for weird output is the string is not NUL terminated. Add this line after second for loop.
name[len] = '\0'; // add this to null terminate your string.
Here is your working Code
should be
scanf("%[^\n]%*c", name);
printf("\nPlease Enter String 2 =\t");
scanf("%[^\n]%*c", abc);
for(i=0;name[i]!='\0';i++)
len++;
for(j=0;abc[j]!='\0';j++){
name[len]=abc[j];
len++;
}
name[len]='\0';
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");