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
問題:
- 程序爲何似乎符合
'\n'
第一個字符'S'
? - 爲什麼最後一行
printf("The string without newline character: %s", string);
根本沒有從字符串中刪除任何內容? - 我該如何讓這個程序做我打算做的事情?
Thx爲答案。它解決了這個問題。儘管如此,問題2仍然是我的一個謎。有人知道那裏發生了什麼? – Sahand
啊,明白了。謝謝! – Sahand