C - 一次读取单个 int
C - Read a single int at the time
我有这个输入:
Input: 2015
我想这样扫描他:
scanf("%1d", &arr);
但这绝对是错误的。我能做什么?
我想按整数接收输入整数,例如 '2','0','1','5' ,而不是 "2015"。
如果您的输入是固定大小的 2015
那么您可以使用
int arr[4];
for(int i=0; i<4; i++){
scanf("%1d", arr+i);
}
但对于一般情况,您可以使用 fgets.
读取字符串
只需单独读取每个字符,并将单独的 char
转换为整数。
#include <stdio.h>
int main(int argc, char* argv[])
{
size_t len, i;
char buff[64];
fgets(buff, sizeof(buff), stdin);
for(i = 0, len = strlen(buff); i < len; ++i) {
int curr = buff[i] - '0'; /* subtracting '0' converts the char to an int */
printf("%d\n", curr);
}
}
我建议阅读整行,然后具体解析。
要在 POSIX 系统上阅读一行,请使用 getline(3), which will allocate the line buffer in heap (don't forget to initialize the pointer containing the line to NULL
and the variable size to 0, and free
the line where you are done). If you are unlucky to be on a system without getline
, declare a large (e.g. 256 bytes at least) buffer and use fgets(3). BTW, on Linux, for editable input from the terminal -a.k.a. a tty- (not a pipe or a file, so test with isatty(3)) you could even consider using readline(3);试试看,非常好用!
一旦整行都在内存中,您就可以对其进行解析(前提是您至少在脑海中定义了该行的语法;一个示例通常是不够的;您可能想要使用 EBNF在你的文档中)。
你可以使用 sscanf(3) to parse that line or parse it manually with some iterative code, etc... Don't forget to check the returned count of scanned items. Perhaps %n
can be handy (to get a byte count). You could also parse that line manually, or use strtol(3) for parsing long
numbers, (or perhaps strtok(3),我不喜欢它,因为它是有状态的)等...
我有这个输入:
Input: 2015
我想这样扫描他:
scanf("%1d", &arr);
但这绝对是错误的。我能做什么? 我想按整数接收输入整数,例如 '2','0','1','5' ,而不是 "2015"。
如果您的输入是固定大小的 2015
那么您可以使用
int arr[4];
for(int i=0; i<4; i++){
scanf("%1d", arr+i);
}
但对于一般情况,您可以使用 fgets.
读取字符串只需单独读取每个字符,并将单独的 char
转换为整数。
#include <stdio.h>
int main(int argc, char* argv[])
{
size_t len, i;
char buff[64];
fgets(buff, sizeof(buff), stdin);
for(i = 0, len = strlen(buff); i < len; ++i) {
int curr = buff[i] - '0'; /* subtracting '0' converts the char to an int */
printf("%d\n", curr);
}
}
我建议阅读整行,然后具体解析。
要在 POSIX 系统上阅读一行,请使用 getline(3), which will allocate the line buffer in heap (don't forget to initialize the pointer containing the line to NULL
and the variable size to 0, and free
the line where you are done). If you are unlucky to be on a system without getline
, declare a large (e.g. 256 bytes at least) buffer and use fgets(3). BTW, on Linux, for editable input from the terminal -a.k.a. a tty- (not a pipe or a file, so test with isatty(3)) you could even consider using readline(3);试试看,非常好用!
一旦整行都在内存中,您就可以对其进行解析(前提是您至少在脑海中定义了该行的语法;一个示例通常是不够的;您可能想要使用 EBNF在你的文档中)。
你可以使用 sscanf(3) to parse that line or parse it manually with some iterative code, etc... Don't forget to check the returned count of scanned items. Perhaps %n
can be handy (to get a byte count). You could also parse that line manually, or use strtol(3) for parsing long
numbers, (or perhaps strtok(3),我不喜欢它,因为它是有状态的)等...