【发布时间】:2013-01-24 17:21:37
【问题描述】:
我不知道如何解析 getline() 中的行。我想看看行中的每个字符。
因此,如果有人在标准输入中输入:“Hello”,我希望能够以这种方式访问 char 数组:
line[0] = 'H'
line[1] = 'e'
line[2] = 'l'
line[3] = 'l'
line[4] = 'o'
line[5] = '/0';
我看过 getchar(),但我想尝试使用 getline(),因为我觉得它更方便。我也看过 scanf(),但它会跳过空格,并且不能像 getchar() 或 getline() 那样很好地解析输入。
这是一个简单的代码,它尝试通过标准输入获取一行的第一个字符,但会导致段错误:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int len;
int nbytes = 100;
char *line = (char *) malloc (nbytes + 1);
while(getline(&line, &nbytes, stdin) > 0){
printf("first char: %s", line[0]); //try and get the first char from input
/**
* other code that would traverse line, and look at other chars
*/
};
return 0;
}
谢谢。
【问题讨论】:
-
printf("first char: %s", line[0]);应该是printf("first char: %c", line[0]);,我认为。 -
为什么
line中的第一个元素使用字符串说明符? -
C 新手。这就是原因。 :)
-
无需将
void*显式转换为char*(在malloc附近)。这是 C,不是 C++,宝贝。