简体   繁体   English

如何将 char c[0] 转移到 int

[英]How can I transfer the char c[0] to int

I read a file with getline, and want to transfer char c[0] to int, I got an error.我用 getline 读取了一个文件,并想将 char c[0] 传输到 int,但出现错误。

error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]
g[n].chicken = atoi(c[0]);
                       ^

In file included from assign.cpp:5:0: /usr/include/stdlib.h:147:12: error: initializing argument 1 of 'int atoi(const char*)' [-fpermissive] extern int atoi (const char *__nptr)在assign.cpp:5:0 包含的文件中:/usr/include/stdlib.h:147:12: 错误:初始化参数 1 of 'int atoi(const char*)' [-fpermissive] extern int atoi (const char *__nptr)

 24        int g;
 25        string str;
 26        while(getline(file,str)){
 27           
 28           const char* ct = str.c_str();
 29           char c[5];
 30           strcpy(c,ct);
 31        
 32
 33           g = atoi(c[0]);

The declaration of atoi looks like this: int atoi(const char* buffer) atoi 的声明如下所示: int atoi(const char* buffer)

You need你需要

g = atoi(c);

because c is the pointer to the character array.因为 c 是指向字符数组的指针。 The array c[5] consists of 5 bytes.数组 c[5] 由 5 个字节组成。 c[0] is the first byte. c[0] 是第一个字节。 c alone is interpreted by the compiler as a pointer to the first byte. c 单独被编译器解释为指向第一个字节的指针。

So, atoi() it takes a pointer to an array of characters.所以, atoi() 它需要一个指向字符数组的指针。 You passed it the first character.你传递了第一个字符。

Using std::getline() to retrieve user input is a great idea.使用 std::getline() 检索用户输入是一个好主意。 Learn to use stringstream to parse items from the getline().学习使用 stringstream 从 getline() 解析项目。 Once you get good at it, you will make fewer mistakes:一旦你擅长它,你就会犯更少的错误:

#include <iostream>
#include <sstream>
#include <string>
#include <fstream>

int main()
{
  int g;

  std::ifstream file;
  file.open ("example.txt");

  std::string str;
  while (getline(file, str)) {
    std::istringstream stream(str);

    stream >> g;

    std::cout << "g is " << g << std::endl;

  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM