2017-07-01 136 views
0

我正在尝试编写一个程序,用于删除用户输入的最后一个换行符,即在用户输入字符串后输入时生成的新行。C:试图从字符串末尾删除换行符

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! 

} 

但它并不像我想的那样行为。下面是输出:

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 

问题:

  1. 程序为何似乎符合'\n'第一个字符'S'
  2. 为什么最后一行printf("The string without newline character: %s", string);根本没有从字符串中删除任何内容?
  3. 我该如何让这个程序做我打算做的事情?
+0

Thx为答案。它解决了这个问题。尽管如此,问题2仍然是我的一个谜。有人知道那里发生了什么? – Sahand

+0

啊,明白了。谢谢! – Sahand

回答

3

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

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

这条线可能是错误的,你给string [i]赋值,而不是比较它。

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