I tried to take 2 integers (smaller than 40000) between a blank like 1232 11232
and then parse it to integer. As you can understand getfirstnum
returns the first number. But the problem is that there is something unusual I couldn't understand. When I type 11232 22312
as an input the output must be same 11232 22312
but it is 2231211232 223121232
. it basically puts the second number in front of first number, it concatenates both numbers and in second one it concatenate the last 4 digits. Why and how to solve it?
PS: I get input with regex to get input with blank (blank is problem in scanf
) it clearly works, I checked it many times. Problem starts in atoi
because before atoi
the string is parsed well.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getfirstnum(char *input);
int getsecnum(char *input);
int main() {
char *input = malloc(40005 * sizeof(char));
int N, target, i = 0, j = 0, x, y, shot = 0, found = 0;
scanf(" %[^\n]s", input);
N = getfirstnum(input);
target = getsecnum(input);
printf("%d %d", N, target);
}
int getfirstnum(char *input) {
int numm, i = 0;
char num1[40005];
while (input[i] != ' ') {
num1[i] = input[i];
i++;
}
fflush(stdout);
numm = atoi(num1);
return numm;
}
int getsecnum(char *input) {
int num, i = 0, j = 0;
char num2[40005];
while (input[i] != ' ')
i++;
i++;
while (i < strlen(input)) {
num2[j] = input[i];
printf("%c", sayi2[j]);
i++;
j++;
}
num = atoi(num2);
return num;
}
Your code shows major confusion between the number value and the number of digits. Your code fails because you do not null terminate the buffers after copying digits from the source. But your code is way too complicated for the task: parsing numbers can be done easily with sscanf()
or strtol()
. All you need is a buffer to read one line:
#include <stdio.h>
int main() {
char line[256];
int N, target;
if (fgets(line, sizeof line, stdin)) {
if (sscanf(line, "%d%d", &N, &target) == 2) {
printf("%d %d\n", N, target);
}
}
return 0;
}
Or using strtol
:
#include <stdio.h>
#include <stdlib.h>
int main() {
char line[256];
int N, target;
char *p, *q;
if (fgets(line, sizeof line, stdin)) {
N = strtol(line, &p, 10);
target = strtol(p, &p, 10);
if (p > line && q > p)
printf("%d %d\n", N, target);
}
return 0;
}