我见过很多地方说sizeof(buf)/sizeof(buf[0])
应该可以用来确定数组的大小,但这对我不起作用
char* buf = NULL;
size_t len;
len = 0;
while(getline(&buf,&len,stdin) >= 0 ){
unsigned int i;
size_t size= sizeof(buf)/sizeof(buf[0]);
for (i = 0; i < size; i++){
char* s;
int pos;
s = strtok(buf, " ");
unsigned int j;
for (j = 0; j < strlen(s); j++){
doStuff();
}
我想确定buf
中有多少个字符串,以便知道需要调用多少次strtok()
才能对单词的每个字母执行某些操作。
答案 0 :(得分:2)
getline()
会返回读取的字符数。如果需要读取的字符数,请使用return。如果您需要strtok
解析的令牌数量,请保留index
并递增它。
len = 0;
ssize_t n = 0; /* number of chars read by getline */
size_t index = 0; /* number of tokens parsed by strtok */
while ((n = getline (&buf, &len, stdin)) >= 0 ) {
...
char *s = buf;
for (s = strtok (s, " "); s; s = strtok (NULL, " ")) {
index++;
...
}
...
for (j = 0; j < index; j++){
doStuff();
}
注意: buf
<{1}} <{1}} strtok
null-terminating
strtok
buf
strtok
}})。如果您稍后需要index = input.indexOf("-");
if(index == 0) {
String substring = input.substring(input.lastIndexOf("-") + 1);
newId = Integer.parseInt(substring);
Store s = new Store(name,id);
,请在致电-
之前制作副本。
答案 1 :(得分:1)
检查getline()的返回值
来自man-page
RETURN VALUE top
On success, getline() and getdelim() return the number of characters
read, including the delimiter character, but not including the
terminating null byte ('\0'). This value can be used to handle
embedded null bytes in the line read.
Both functions return -1 on failure to read a line (including end-of-
file condition). In the event of an error, errno is set to indicate
the cause.