Sahand
Sahand

Reputation: 8350

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:

  1. Why does the program seem to match the '\n' with the first character 'S'?
  2. 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?
  3. How can I make this program do what I intend it to do?

Upvotes: 0

Views: 443

Answers (3)

Giles.Spreadborough
Giles.Spreadborough

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

haccks
haccks

Reputation: 105992

The condition (string[i] = '\n') will always return true. It should be (string[i] == '\n').

Upvotes: 3

Huan Jiang
Huan Jiang

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

Related Questions