c++ - 无法将字符串从命令行转换为 float 组

标签 c++

char * temp_array;

strcpy(temp_array, argv[i + 1]);

            for(int j = 0; j < 8; j++)
            {
                fann_input[j] = atoi(temp_array[j]);
                printf("%f\n", fann_input[j]);
                printf("o%c\n", temp_array[j]);
            }

fann_input 是一个 float 组。

在 atoi 行,我得到错误:

src/main.cpp: In function ‘int main(int, const char**)’:
src/main.cpp:117: error: invalid conversion from ‘char’ to ‘const char*’
src/main.cpp:117: error:   initializing argument 1 of ‘int atoi(const char*)’

有什么想法吗?

每个字符要么是 1 要么是 0

最佳答案

各种Bad在这里:

  1. 您正在尝试将字符串复制到未初始化的 char*(temp_array 已声明但从未初始化)

  2. atoi 需要一个指向整个字符串的指针,但您传递给它的是单个字符 (temp_array[j])

  3. fann_input 是一个 float 数组(你说)但你试图用 int 填充它(这是atoi 返回什么)

  4. 您在 C++ 中使用 C 构造(指针、atoi 等)

  5. 您一遍又一遍地回避相同的命令行参数。

按照这些思路做更多的事情。未编译的伪代码如下。错误处理留给您作为练习。

for( int j = 0; j < 8; ++j )
{
  stringstream ss;
  ss << argv[j+1]; // copy cmd line param to stream
  float val = 0.0f;
  ss >> val;  // convert to a float
  fann_input[j] = val;  // save it!
}

关于c++ - 无法将字符串从命令行转换为 float 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5423260/

相关文章:

c++ - 从模板参数派生的类没有 protected 成员访问

c++ - for循环中的赋值语句

c++ - 查找 vector 中位于指定范围内的元素

c++ - ctype、字符串和容器

C++检测用户何时按下箭头键

C++ UDP RecvFrom、SendTo 不同套接字

c++ - 如何衡量 pimpl 候选人?

c++ - 访问对象void pointer c++的成员

c++ - 在opencv中将2张图像与透明蒙版结合起来

c++ - 模板 C++ 与 GCC