2014-09-25 46 views
-4

我一直在寻找一个解决方案,这一点,并没有发现任何,我一直在试图让一个字符串,它的大小,用户输入,有没有什么办法去关于这样做? (我试图消除char数组中的空值)。获取准确的用户输入,C

编辑:我很抱歉关于失踪信息,编译器是gcc -std = C99,操作系统是Ubuntu Linux系统。

这里是我要集中于+报头(未完全完成),我试图创建一个字符串,它是长度相同用户输入的主程序的一部分,并且包含相同的值。

编译器目前无法识别myalloc和函数getline

#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 

int main() { 
    char *string; 
    int selection, bytes_read, nbytes = 255; 
    unsigned char key, letter; 

    do { 
    ... 
    printf("Enter a sentence:\n"); 
    string = (char *) myalloc(nbytes + 1); 
    bytes_read = getline(&string, &nbytes, stdin); 
    ... 
    }while(..); 
} 
+2

http://crasseux.com/books/ctutorial/getline.html – 2014-09-25 17:19:37

+0

'getline'可能是答案,但我觉得你的问题还不清楚。你称之为用户输入的大小是什么?怎么样从管道获取输入? – 2014-09-25 17:22:58

+0

我认为getline是在POSIX中定义的。你使用哪种操作系统/编译器? – 2014-09-25 17:24:28

回答

0

以下内容作为main.c

#define _POSIX_C_SOURCE 200809L 

#include <stddef.h> 
#include <stdio.h> 
#include <stdlib.h> 

int 
main() 
{ 
    size_t n = 0; 
    char * line = NULL; 
    ssize_t count; 
    printf("Enter a sentence: "); 
    count = getline(&line, &n, stdin); 
    if (count < 0) 
    { 
     perror("getline"); 
     return EXIT_FAILURE; 
    } 
    /* If it bothers you: get rid of the terminating '\n', if any. */ 
    if (line[count - 1] == '\n') 
    line[count - 1] = '\0'; 
    printf("Your input was: '%s'\n", line); 
    free(line); 
    return EXIT_SUCCESS; 
} 

然后,在终端:

$ gcc -o main main.c 
$ ./main 
Enter a sentence: the banana is yellow 
Your input was: 'the banana is yellow' 

有也是使用0的更广泛的例子包含在其man page中的。