简体   繁体   中英

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?

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

if((string[i] = '\n'))

这行可能是错误的,您是将值分配给string [i],而不是对其进行比较。

if((string[i] == '\n'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM