Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C: 试图从字符串末尾删除换行字符_C_Newline - Fatal编程技术网

C: 试图从字符串末尾删除换行字符

C: 试图从字符串末尾删除换行字符,c,newline,C,Newline,我正试图编写一个程序,从用户输入中删除最后一个换行符,即用户在键入字符串后点击enter键时生成的换行符 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

我正试图编写一个程序,从用户输入中删除最后一个换行符,即用户在键入字符串后点击enter键时生成的换行符

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!

}
问题:

  • 为什么程序似乎将
    '\n'
    与第一个字符
    'S'
    匹配
  • 为什么最后一行
    printf(“没有换行符的字符串:%s”,string)当我没有从字符串中删除任何内容时,是否完全不生成输出
  • 我怎样才能使这个程序达到我的目的呢
  • 条件
    (字符串[i]='\n')
    将始终返回
    true
    。它应该是
    (字符串[i]='\n')

    条件
    (字符串[i]='\n')
    将始终返回
    true
    。它应该是
    (字符串[i]='\n')

    这一行可能是错误的,您正在为字符串[i]赋值,而不是比较它

    if((string[i] == '\n'))
    
    这一行可能是错误的,您正在为字符串[i]赋值,而不是比较它

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

    谢谢你的回答。它解决了这个问题。不过,第二个问题对我来说仍然是个谜。有人知道那里发生了什么吗?啊,知道了。谢谢谢谢你的回答。它解决了这个问题。不过,第二个问题对我来说仍然是个谜。有人知道那里发生了什么吗?啊,知道了。谢谢
    if((string[i] == '\n'))