Suppose there are numbers 156, 13, 42, 12, 123, and I need their number - 5.
What function to use?
strlen(int_a); или int_a.length(); Suppose there are numbers 156, 13, 42, 12, 123, and I need their number - 5.
What function to use?
strlen(int_a); или int_a.length(); It depends on how these numbers are organized.
If this is an array whose size is known at compile time:
int a[]={156, 13, 42, 12, 123};
you can use the expression sizeof a / sizeof a[0] .
If they are in a standard container like std::vector<int> , then there is a member function size() .
If the format is exactly this - "156, 13, 42, 12, 123", then count the number of commas and increase by one.
@ bellator001 , you were rightly told that there is no one library function. Depending on the format of the data in the string will have to use different functions.
avp@avp-xub11:hashcode$ cat cc #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> char * strtos (char **p, const char *delim) { char *word = 0; if (*((*p) += strspn(*p, delim))) { word = *p; (*p) += strcspn(*p, delim); } return word; } int main (int ac, char *av[]) { int rc = 1, n = 0, d; if (av[1]) { if (isdigit(av[1][0])) { FILE *f = fmemopen(av[1], strlen(av[1]), "r"); while (fscanf(f, "%d", &d) == 1) n++; rc = !feof(f); fclose(f); } else { char *w, *ep = av[1]; int err = 0, l; while (w = strtos(&ep, " ,")) { char *p, buf[(l = ep - w) + 1]; strncpy(buf, w, l); buf[l] = 0; strtol(buf, &p, 10); if (!*p) n++; else err++; } rc = err > 0; } printf ("%d numbers (%s)\n", n, rc ? "Err" : "OK"); } return rc; } avp@avp-xub11:hashcode$ g++ cc avp@avp-xub11:hashcode$ ./a.out ' 1, 2, 33, 4, 616' 5 numbers (OK) avp@avp-xub11:hashcode$ ./a.out '1, 2, 33, 4, 616' 1 numbers (Err) avp@avp-xub11:hashcode$ ./a.out ' 1 2 33' 3 numbers (OK) avp@avp-xub11:hashcode$ ./a.out '1 2 33' 3 numbers (OK) avp@avp-xub11:hashcode$ I intend not to write comments in this program, but gave its output for various inputs in order to somewhat simplify the @ bellator001 parsing process.
fmemopen . - Im ieeeif (isdigit... and controls the choice of the method of their reading. As for the non-standard fmemopen - yes, Windows fans are not lucky ... - So the choice is obvious - use strtos() (or your analog). - avpSource: https://ru.stackoverflow.com/questions/407300/
All Articles