我不知道如何解析 getline() 中的行。我想看看该行中的每个字符。
因此,如果有人在标准输入中输入:“Hello”,我希望能够以这种方式访问 char 数组:
line[0] = 'H'
line[1] = 'e'
line[2] = 'l'
line[3] = 'l'
line[4] = 'o'
line[5] = '/0';
Run Code Online (Sandbox Code Playgroud)
我看过 getchar(),但我想尝试使用 getline(),因为我觉得它更方便。我也研究过 scanf(),但它会跳过空格,并且不能让我像 getchar() 或 getline() 那样很好地解析输入。
下面是尝试通过 stdin 获取行的第一个字符的简单代码,但会导致段错误:
#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;
}
Run Code Online (Sandbox Code Playgroud)
谢谢。
使用%c格式说明符打印出单个字符。
代码
printf("first char: %s", line[0])
Run Code Online (Sandbox Code Playgroud)
将尝试将其视为line[0]char 数组的地址。如果只想打印第一个字符,请将其更改为
printf("first char: %c", line[0])
// ^
Run Code Online (Sandbox Code Playgroud)
您可以考虑在代码的其他部分进行一些其他小的更改:
free(line)在 while 循环之后| 归档时间: |
|
| 查看次数: |
3500 次 |
| 最近记录: |