我正在使用c语言,以下是我的代码:
#define _GNU_SOURCE
#include<stdio.h>
#include<stdlib.h>
int main()
{
char* str = NULL;
size_t n;
printf("Enter the string : \n");
getline(&str, &n, stdin);
printf("Initial string is : (%s)\n", str);
return 0;
}
当我运行上面的程序时,它会给出以下输出:
Enter the string :
bsalunke
Initial string is : (bsalunke
)
意外的字符串存储在 str
指针中可能是什么原因(即它是一个带有许多空格的字符串)?
我在 Linux 上使用 gcc 4.1.2 版本
最佳答案
来自 getline 的手册页
getline() reads an entire line from stream, storing the address of the buffer containing the text into *lineptr. The buffer is null-terminated and includes the newline character, if one was found.
我认为这可以解释这一点。它不是一个有很多空格的字符串,而是一个以换行符结尾的字符串。
关于c - 使用 getline() 从 stdin 读取整行时出现意外输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15268226/