Reputation: 8350
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:
'\n'
with the first character 'S'
?printf("The string without newline character: %s", string);
generate no output at all when I haven't deleted anything from the string?Upvotes: 0
Views: 443
Reputation: 1
You could use the strlen() command from the string.h library to find the length of the string, then set that element of the string to 0
#include <string.h>
name[strlen(name)] = 0;
strlen() will return the length of the entered string regardless of the amount of memory allocated to it, so you don't have to traverse the entire string with the for() loop.
Upvotes: 0
Reputation: 105992
The condition (string[i] = '\n')
will always return true
. It should be (string[i] == '\n')
.
Upvotes: 3
Reputation: 257
if((string[i] = '\n'))
this line may be wrong, you are assign value to string[i], not compare it.
if((string[i] == '\n'))
Upvotes: 2