2017-07-01 5 views
0

最後の改行をユーザー入力から削除しようとしています。つまり、ユーザーが文字列を入力した後にEnterキーを押したときに生成されます。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. はなぜプログラムは、最初の文字'S''\n'と一致するように見えるのでしょうか?
  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')) 

この行が間違っている可能性があり、あなたは[i]は、それを比較しない文字列に割り当てる値です。

if((string[i] == '\n')) 
関連する問題