c - 使用 getline() 从 stdin 读取整行时出现意外输出?

标签 c linux

我正在使用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/

相关文章:

java.text.ParseException : Unparseable date: "1901-01-01 00:00:00" 异常

linux - 在 shell 脚本中获取命令输出

linux - 为arm编译libcurl应用程序时出错

c - 程序查找三个输入数字中的最大和最小,并显示识别的最大/最小数字是偶数还是奇数

c - 如何在 C 中计算 pow()?

C:在不强制转换的情况下对无符号变量执行有符号比较

linux - 在 linux 中用条件交换列

c++ - 以 clang 格式对齐函数声明

c++ - C/C++ : goto into the for loop

linux - 为什么 UNIX 用户必须有密码?