Answer the question
In order to leave comments, you need to log in
Why does the function output zeros?
Task: write a C program that looks for a number in a string and displays it on the screen. For example, the string "aaa010101bbb343ccc" - the program must first find the number 010101, display it on the screen, then the program must find the number 343 and display it on the screen.
My code:
int func(char a[]) {
for (int i = 0; i < strlen(a); i++)
{
char nummas[100];
int num = 0;
int numcount = 0;
if (a[i] >= '0' && a[i] <= '9') {
nummas[i] = a[i];
}
else {
num = atoi(nummas);
printf("%d", num);
continue;
}
}
}
int main()
{
char f[100] = "
func(f);
}
for some reason, the response is zeros.
Answer the question
In order to leave comments, you need to log in
nummas[i] = a[i];
here you add the found digit to the nummas buffer not from the beginning of the string, but from position i which is already in the middle for it, and since the string is initially filled with zeros, atoi thinks that the string is empty and returns 0
you must also create a variable for the character number in nummas and do not forget to add a symbol with code 0 to atoi to overwrite the previous value (otherwise, if you first find a long number and then a short one, the output will mix the short number with the long one) I
strongly recommend debugging your program, going through the entire algorithm step by step and checking what should be in each variable and what your program puts there, all errors will immediately become visible
There are small bugs when dealing with C-style strings and array indexes. I rewrote the function a little, it seems to work.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void func(char a[])
{
int startIndex = 0;
int endIndex = 0;
for (int i = 0; i < strlen(a); i++)
{
int num = 0;
int numcount = 0;
if (a[i] >= '0' && a[i] <= '9')
{
// Ищем начальный и конечный индексы числа.
startIndex = i;
endIndex = strlen(a) - 1; // вычитаем 1 т.к. исключаем 0-символ.
for (int j = startIndex; j < strlen(a); j++)
{
if (a[j] < '0' || a[j] > '9')
{
endIndex = j - 1;
break;
}
}
// формируем число.
char number[100];
int k = 0;
for (int l = startIndex; l <= endIndex; l++)
{
number[k] = a[l];
k++;
}
number[k] = '\0'; // Строки в стиле C должны заканчиваться 0-символом.
printf("%d\n", atoi(number));
i = endIndex;
}
}
}
int main()
{
char f[100] = "aaa010101bbb343ccc";
func(f);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question