I have a program that takes a char array and calls the function convert. The function determines whether the character is a letter or number. The program is supposed to output the first letter it finds in the string. and the first numbers it finds in the string. My loop to stop looking for letters after it finds one isn't working.
Any thoughts?
Code is written in C using the Borland Compiler.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int convert (char array[],char **);
int main()
{
int intval;
char array[512], *charptr;
printf("Input a string that starts with a series of decimal digits:\n>");
while ( gets( array ) != NULL ){
intval = convert(array, &charptr );
printf ("Intval contains %d, Charptr contains '%s'\n", intval, charptr);
}
system("pause");
return 0;
}
int convert (char array[],char ** charptr)
{
int i, x, c = 0;
char b[512];
for (i=0;i<strlen(array);i++){
if (isalpha(array[i]))
{
if(c >= 1){
*charptr = &array[i];
c++;
}
else
break;
}
else if ( isdigit(array[i]))
x = 10*x + array[i] - '0';
}
return x;
}
UPDATE:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int convert (char array[],char ** charptr);
int main()
{
int intval;
char array[512], *charptr;
printf("Input a string that starts with a series of decimal digits:\n>");
while ( gets( array ) != NULL ){
intval = convert(array, &charptr );
printf ("Intval contains %d, Charptr contains '%s'\n", intval, charptr);
}
system("pause");
return 0;
}
int convert (char array[],char ** charptr)
{
int i, x, c;
char b[512];
for (i=0;array[i] != 0;i++){
if ( isdigit(array[i]))
x = 10*x + array[i] - '0';
else if (isalpha(array[i]))
{
c++;
if(c >= 1){
*charptr = &array[i];
}
}
}
return x;
}
You have a logic error. c is initialized to 0. There is a line to increment c but it is inside an if block that will never be true.
if(c >= 1){
*charptr = &array[i];
c++;
}
Catch 22???
Perhaps you meant to use:
int convert (char array[],char ** charptr)
{
int i, x, c = 0;
char b[512];
for (i=0;i<strlen(array);i++){
if (isalpha(array[i]))
{
// No need for checking the value of c
// return as soon you find an alphabet.
*charptr = &array[i];
break;
}
else if ( isdigit(array[i]))
// If you are looking for an alphabet only,
// why do you have this block of code???
x = 10*x + array[i] - '0';
}
return x;
}
Update
Perhaps, this is what you are looking for.
int convert (char array[], char ** charptr)
{
size_t i;
int x = 0;
size_t len = strlen(array);
// Set charptr to NULL in case there are no letters in the input.
*charptr = NULL;
for (i=0;i<len;i++){
if ( isalpha(array[i]))
{
*charptr = &array[i];
return x;
}
else if ( isdigit(array[i]))
{
x = 10*x + array[i] - '0';
}
}
return x;
}
int scanString(char array[],char * charptr)
{
int len = strlen(array);
int digs = 0;
int x = 0;
*charptr = 0;
for (int i=0;i<len;i++){
if (charptr == 0 && isalpha(array[i]))
{
*charptr = array[i];
}
else if (digs == 0 && isdigit(array[i])){
x = array[i] - '0';
digs = 1;
}
if(digs > 0 && charptr != 0)
break;
}
return x;
}
the spec says return the first character found so changed the charptr.
Related
bool in_array(char a[], char input, int len){
for (int l = 0; l < len; l++){
}
}
return false;
}
int main(void) {
char i = 'l';
int count = 0;
int count_d = 0;
char a[1000] = {0};
else{
count_d++;
}
}
printf("%d\n", count_d);
}
this is the code i have but this returns numbers of times it has duplicated
as there are two characters a and b
If you have learnt only arrays and do not know how to allocate memory dynamically then use a second array to store unique duplicated characters.
Here is a demonstrative program.
#include <stdio.h>
#include <stdbool.h>
bool in_array( const char a[], size_t n, char c )
{
size_t i = 0;
while ( i != n && a[i] != c ) i++;
return i != n;
}
int main(void)
{
enum { N = 128 };
char a[N];
char b[N / 2];
size_t count_duplicates = 0;
size_t count = 0;
char c;
while ( count < N && scanf( " %c", &c ) == 1 )
{
if ( !in_array( a, count, c ) )
{
a[count++] = c;
}
else if ( !in_array( b, count_duplicates, c ) )
{
b[count_duplicates++] = c;
}
}
printf( "There are %zu duplicated character(s).\n", count_duplicates );
return 0;
}
If to enter the sequence of characters
aaabbaaac
then the program output will be
There are 2 duplicated character(s).
i hope it will help you :
`#include <unistd.h>
#include <stdio.h>
#include <string.h>
int in_a(char *a, char c)
{
for (int i = 0; i < strlen(a); i++)
if (a[i] == c)
return 0;
return (1);
}
int main(int ac, char **av)
{
int count_duplicates = 0;
int same = 0;
char old = 0;
char new[128] = {0}; // i
int count = 0;
char *a = av[1];
while (a[count] != '\0') {
if (old != a[count] && in_a(new, a[count])) {
same = 0;
}
if (a[count] == old && same != 1) {
count_duplicates += 1;
same = 1;
}
old = a[count];
new[count] = a[count];
count += 1;
}
printf("%i\n", count_duplicates);
return (0);
}`
I'm trying to write a function which changes letters into two asterisks (*) using pointers.
For example:
Input: hello12345good++//--ok
Output: **********123456********++//--****
I've writen one that changes letters into two of the same letters, but couldn't write the same for *.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int points_converter(char str[])
{
char *s, *s1;
int f = 0;
for (s = str; *s; s++)
{
if(isalpha(*s))
{
f = 1;
s1 = s;
s = s + strlen(s);
while(s != s1 - 1)
*(s+1) = *(s--);
s = s + 2;
}
}
return f;
}
int main()
{
char str[81];
int f;
puts("Input string:");
while (strlen(gets(str)) >= 81);
f = points_converter(str);
if (f == 0)
{
puts("No latin letters in string.");
}
else
{
puts("New string: ");
puts(str);
}
return 0;
}
like this
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdbool.h>
bool points_converter(char str[]){
bool f = false;
char *temp = malloc(strlen(str)*2+1);
char *s = str, *d = temp;
if(!temp){
perror("malloc:");
return f;//no change
}
for (; *s; s++){
if(isalpha((unsigned char)*s)){
f = true;
*d++ = '*';
*d++ = '*';
} else {
*d++ = *s;
}
}
*d = 0;
strcpy(str, temp);//`str` must have enough spaces.
free(temp);
return f;
}
#define MAX_LENGTH 40
int main(void){
char str[MAX_LENGTH * 2 + 1];
while(true){
puts("Input string:");
fgets(str, MAX_LENGTH+1+1, stdin);//+1:newline, +1:NUL. Use fgets instead of gets
char *p = strchr(str, '\n');
if(p){
*p = '\0';//chomp newline
break;
} else {
while (getchar() != '\n');//Input too long, clear input
}
}
if (points_converter(str)) {
puts("New string: ");
puts(str);
} else {
puts("No latin letters in string.");
}
return 0;
}
how about:
static const int MAXINPUTLEN=81;
int points_converter(const char* input, char *output)
{
int count = 0; // initialize counter to zero
while (*input) { // while input is not pointing to zero
if (isalpha(*input)) { // if input is pointing to alpha
output[0] = '*'; // replace first byte pointed to by output with '*'
output[1] = '*'; // replace 2nd byte pointed to by output with '*'
output += 2; // increment output by 2
count++; // increment counter
} else {
*output = *input; // copy non-alpha to output
output++; // increment output by one
}
input++; // increment input pointer by one
}
*output = 0; // terminate output with zero byte
return count; // return count
}
int main()
{
char input[MAXINPUTLEN + 1];
char output[2 * MAXINPUTLEN + 1];
gets(input); // not checking for input overflow!
points_converter(input, output);
}
I wanna ask how it can not get integer from a string
for example, here are my code:
int main() {
char str[] = "ababbababa-1998";
int nr = atoi(str);
printf("%d\n", nr);
return (EXIT_SUCCESS);
}
when running, it print out 0 but not 1998, how can I fix it ?
In your case you can use strtok.
int main() {
char str[] = "ababbababa-1998";
char * const first_part = strtok(str, "-");
if (first_part == NULL) {
return 1;
}
char * const second_part = strtok(NULL, "-");
if (second_part == NULL) {
return 1;
}
int nr = atoi(second_part);
printf("%d\n", nr);
return 0;
}
You can look at Why is there no strtoi in stdlib.h? for error check atoi.
Keep walking down str() until code finds something numeric using strtol().
int main() {
char str[] = "ababbababa-1998";
char *p = str;
char *endptr;
while (*p) {
long number = strtol(p, &endptr, 10);
// Was conversion successful?
if (endptr != p) {
printf("%ld\n", number);
return EXIT_SUCCESS;
}
p++;
}
puts("No conversion");
return EXIT_FAILURE;
}
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define ASCII '0'
int
main(void) {
char const str[] = "ababbababa-1998";
int i, result = 0;
for (i = 0; str[i]; i++) {
if (isdigit(str[i])) {
result *= 10;
result += str[i] - ASCII;
}
}
printf("number = %d\n", result);
return 0;
}
If you want to extract all the numeric digits from a string you could use this function I created.
You will need these header files for this function to work.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void getNumbers(char data[]) {
int index = 0;
char current;
for( int i = 0; i < strlen(data); ++i ) {
current = data[i];
if (current >= 48 && current <= 57) {
data[index++] = current;
}
}
data[index] = '\0';
}
You can use the above function like this.
char foobar[] = "1A2B3C4D5E6F7G8H9I";
getNumbers(foobar);
printf("%s", foobar);
The above code will output 123456789
If I got char* "12345" and I want to convert to int with a recursive function, how can I do that ?
This is a simple way how to convert char to int with loop.
while (str[i]) {
new_num *= 10;
new_num += str[i++] - '0';
}
If "rexrsia/rxursia way" means the recursive way, here's one way to do it:
#include <stdio.h>
#include <string.h>
int convert_with_length(char* sz, int cch) {
// base case: empty string
if (cch == 0) {
return 0;
}
// recursive case, use the last digit and recurse on the rest:
// e.g. "12345" becomes 10 * convert("1234") + 5
return (sz[cch - 1] - '0') + (10 * convert_with_length(sz, cch - 1));
}
int convert(char *sz) {
return convert_with_length(sz, strlen(sz));
}
int main() {
char* str = "12345";
printf("result = %d\n", convert(str));
}
Yet another variant without length calculation:
#include <stdio.h>
int convert_(char* s, int r) {
return *s ? convert_(s + 1, r * 10 + (*s - '0')) : r;
}
int convert(char* s) {
return convert_(s, 0);
}
void main()
{
printf("%d", convert("123456"));
}
I just tried with only one function to convert string to integer may be helpful,
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int strtoint(char *ptr)
{
int num;
char *str = NULL;
if(strlen(ptr) == 0)
return 0;
else if(strlen(ptr) == 1)
return ptr[strlen(ptr)-1]-48;
else
{
str = (char *) malloc(strlen(ptr)-1);
strcpy(str,ptr);
str[strlen(ptr)-1]='\0';
num = (strtoint(str) * 10) + ptr[strlen(ptr)-1]-48;
free(str);
return num;
}
}
int main(void)
{
printf("converted string %d\n",strtoint("12345"));
}
Trying to get scanf to iterate and evaluate each section of the string with isdigit. However it seems to be skipping the first 'block' thus offsetting everything. Recommendations on what I'm doing wrong?
int main (void) {
int icount = 0;
int c = 0;
int compare = 0;
int len = 0;
char s[256] = "";
printf("Enter a string:\n\n");
while (scanf("%s", s) == 1) {
scanf("%255s", s);
len = strlen(s);
printf("the string is %d characters long\n", len);
while (len > 0) {
printf("c is on its s[%d] iteration\n", c);
if (isdigit(s[c])) {
compare = compare + 1;
}
c++;
len--;
}
if (compare == strlen(s)) {
icount = icount + 1;
}
c++;
}
printf("\ni count is %d\n", icount);
return 0;
}
When I run it I keep getting data back like this:
./a
Enter a string:
17 test 17
the string is 4 characters long
c is on its s[0] iteration
c is on its s[1] iteration
c is on its s[2] iteration
c is on its s[3] iteration
the string is 2 characters long
c is on its s[5] iteration
c is on its s[6] iteration
i count is 0
From the comments above, I believe this might be what you are looking for
#include <ctype.h>
#include <stdio.h>
int main (void)
{
int icount;
int index;
char string[256];
printf("Enter a string:\n\n");
icount = 0;
while (scanf("%255s", string) == 1)
{
int isNumber;
isNumber = 1;
for (index = 0 ; ((string[index] != '\0') && (isNumber != 0)) ; ++index)
{
printf("index is on its string[%d] iteration\n", index);
if (isdigit(string[index]) == 0)
isNumber = 0;
}
if (isNumber != 0)
icount += 1;
}
printf("\nicount is %d\n", icount);
return 0;
}
ended up going with this simple code as my knowledge level is... well... simple
. thanks for the help with that iteration and second scanf it was about to drive me over the edge!
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main (void) {
int icount = 0;
int c = 0;
int compare = 0;
char s[256] = "";
printf("Enter a string:\n\n");
while (scanf("%255s", s) == 1) {
compare = 0;
for (c = 0 ; s[c] != '\0' ; c++) {
if (isdigit(s[c])) {
compare = compare + 1;
}
}
if (compare == strlen(s)) {
icount = icount + 1;
}
}
printf("%d integers\n", icount);
return 0;
}