atoi() 转换错误
atoi() 给了我这个错误:
error C2664: 'atoi' : cannot convert parameter 1 from 'char' to 'const char *'
Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
从这一行: int pid = atoi( token.at(0) ); 其中 token 是一个向量
我该如何解决这个问题?
atoi() is giving me this error:
error C2664: 'atoi' : cannot convert parameter 1 from 'char' to 'const char *'
Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
from this line:
int pid = atoi( token.at(0) );
where token is a vector
how can i go around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
token.at(0) 返回单个字符,但 atoi() 需要一个字符串(指向字符的指针)。要么将单个字符转换为字符串,要么将单个数字字符转换为它代表的数字通常可以*这样做:
* 例外情况是字符集没有按顺序编码数字 0-9,这种情况极为罕见。
token.at(0) is returning a single char, but atoi() is expecting a string (a pointer to a char.) Either convert the single character to a string, or to convert a single digit char into the number it represents you can usually* just do this:
* The exception is when the charset doesn't encode digits 0-9 in order which is extremely rare.
您必须创建一个字符串:
... 假设 token 是 char 的 std::vector ,并使用接受单个字符的 std::string 构造函数(以及字符串将包含的该字符的数量,一个在这种情况下)。
You'll have to create a string:
... assuming that token is a std::vector of char, and using std::string's constructor that accepts a single character (and the number of that character that the string will contain, one in this case).
您的示例不完整,因为您没有说出向量的确切类型。 我假设它是 std::vector(也许,您用 C 字符串中的每个字符填充)。
我的解决方案是在 char * 上再次转换它,这将给出以下代码:
请注意,这是一个类似 C 的解决方案(即,在 C++ 代码中相当难看),但它仍然有效。
Your example is incomplete, as you don't say the exact type of the vector. I assume it is std::vector<char> (that, perhaps, you filled with each char from a C string).
My solution would be to convert it again on char *, which would give the following code:
Note that this is a C-like solution (i.e., quite ugly in C++ code), but it remains efficient.
例子:
Example: