0

我有一个简单的程序,我想将输入存储到矩阵中以便于访问。我在将简单的字符串字符转换为 int 时遇到问题,有人可以解释为什么我的代码在尝试编译时给我这个消息吗?

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’

问题似乎与我使用 c_str() 函数有关,但如果我没记错的话,这是将字符转换为 int 值所必需的。

我的代码:

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

1 回答 1

0

采用:

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

您不需要使用atoi单个数字,它的数值只是它的偏移量'0'

但如果你真的想使用atoi,你将不得不创建一个单独的字符串:

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;
}
于 2014-12-23T03:49:55.317 回答