I need to calculate the size of a string in order to apply a function (the function applied is going to depend on the size of valor.)
However, as you can see in this example, I am having some trouble using strlen in the string (in the example you can see I inserted 2 'valor' and the given strlen was 6).
Here is the code, and next to it an image of the process returned.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
char valor[5];
char naipe[5];
int c;
int i = 0;
do {
c = getchar();
if (((c > '0') && (c < '9')) || (c == 'K') || (c == 'Q') || (c == 'J') ||
(c == 'A') || (c == 'T')) {
valor[i] = c;
continue;
}
if ((c > 'A') && (c < 'Z')) {
naipe[i] = c;
i++;
}
} while (c != '\n');
printf("%ld", strlen(valor));
return 0;
}
you have two arrays and you should use two counters for them ,otherwise you would probably skip some elements of each arrays.
also you should terminate char valor[5]
and char naipe[5]
with '\\0'
.
int main() {
char valor[5];
char naipe[5];
int c;
int i = 0,j=0;
do {
c = getchar();
if (((c > '0') && (c < '9')) || (c == 'K') || (c == 'Q') || (c == 'J') ||
(c == 'A') || (c == 'T')) {
valor[j] = c;
j++;
continue;
}
if ((c > 'A') && (c < 'Z')) {
naipe[i] = c;
i++;
}
} while (c != '\n');
valor[j] = '\0';//terminate first then print.
printf("%ld", strlen(valor));
naipe[i] = '\0';
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.