0

I have a simple program where I want to store the input into matrices for easy access. I am having trouble converting a simple string character into an int, can someone explain why my code is giving me this message when I try and compile?

acm.cpp:20:42: error: request for member ‘c_str’ in ‘temp.std::basic_string<_CharT, _Traits, _Alloc>::operator[]<char, std::char_traits<char>, std::allocator<char> >(((std::basic_string<char>::size_type)j))’, which is of non-class type ‘char’

The problem seems to be with my use of the c_str() function, but if i'm not mistaken this is necessary for converting characters into int values.

My code:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
   // read input from console
  int N, M;
  cin >> N; // number of people
  cin >> M; // max number of topics

  // read in binary numbers into matrix
  int binaryNumbers[N][M];
  for (int i = 0; i < N; i++) {
    string temp;
    cin >> temp;
    for (int j = 0; j < M; j++) {
      binaryNumbers[i][j] = atoi(temp[j].c_str());
      cout << binaryNumbers[i][j] << endl;
    }
  }

  return 0;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
mudejar
  • 177
  • 1
  • 2
  • 11

1 Answers1

0

Use:

binaryNumbers[i][j] = temp[j] - '0';

You don't need to use atoi for a single digit, its numeric value is simply its offset from '0'.

But if you really want to use atoi, you will have to create a separate string:

for (int j = 0; j < M; j++) {
    char digit[2] = "0";
    digit[0] = temp[j];
    binaryNumbers[i][j] = atoi(digit);
    cout << binaryNumbers[i][j] << endl;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • That's perfect, it's working now! Is there any benefit to using one over the other complexity wise? – mudejar Dec 23 '14 at 03:56
  • The first one is simpler. The second one performs an unnecessary function call, but it avoids having to know the property of character coding systems that digits are consecutive characters. It would also be easier to adapt it to other radixes that don't have that property. – Barmar Dec 23 '14 at 03:58