Simple problem

Hello! I have this code below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cctype>
using namespace std;

int main()
{
    char x[1], y[1];
    int a,b;
    cout<<"a = ";
    cin.getline(x, 1);
    if(isdigit(x[0]))
    {
        a = atoi(x);
    }
    else
    {
        cout<<"Invalid data!";
        return 0;
    }
    cout<<"b = ";
    cin.getline(y, 1);
    if(isdigit(y[0]))
    {
        b = atoi(y);
    }
    else
    {
        cout<<"Invalid data!";
        return 0;
    }
    cout<<"-b/a = "<<-b/a;
    return 0;
}

I am trying to read 2 values and to check if they are numbers. I read them as char-arrays and then I check with the isdigit() function to see if they are numbers. If so, I transform them in integers by using the function atoi. The problem is that when I execute the program, I write any value for a and then it says "invalid data". It doesn't allow me to read the other variable - b. Where is the problem?
Thank you.
b = atoi(y);

y is an array, so this (from a C point of view ) is the same thing as a pointer.

So it will work if you do this:

b = atoi(y[0]);




Nope, that doesn't work. I tried that at the begining of the implementation. It gives me an error which sais: invalid conversion from 'char' to 'const char*'
It's been so long since I have used atoi , I forgot how it works.

This is the example from the reference on this site.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* atoi example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int i;
  char szInput [256];
  printf ("Enter a number: ");
  fgets ( szInput, 256, stdin );
  i = atoi (szInput);
  printf ("The value entered is %d. The double is %d.\n",i,i*2);
  return 0;
}
I've already seen that but it doesn't help me at all. You see that the argument of atoi is the pointer of that string. My problem is that atoi is not used, it doesn't allow me to read the second value, is a kind of buffer-problem or something like that.
You need to make room for the null terminator in your array (make it [2]).

Note the amount of characters that getline() reads
http://www.cplusplus.com/reference/iostream/istream/getline/
That's right! It works perfectly! Thank you everybody!
Topic archived. No new replies allowed.