gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:49:56 24 4
gpt4 key购买 nike

我正在尝试编写一个程序,从用户输入中删除最后一个换行符,即用户在输入字符串后按回车键时生成的换行符。

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. 我怎样才能让这个程序按照我的意图去做?

最佳答案

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

关于C:尝试从字符串末尾删除换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44864737/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com