Search code examples
c++atoic-str

Error trying to convert string char into int


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;
}

Solution

  • 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;
    }