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