字符串到int的转换

编程入门 行业动态 更新时间:2024-10-09 15:25:00
本文介绍了字符串到int的转换-结果始终为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

#include "stdafx.h" #include <stdlib.h> #include <iostream> #include <string> using namespace std; //#include <stdlib.h> // for itoa() call //#include <stdio.h> // for printf() call int main() { string strConvert; cout<<"sentence"<<endl; cin>>strConvert; int intReturn; intReturn = atoi(strConvert.c_str()); cout<<intReturn<<endl; }

推荐答案

当我执行您的程序时,它给我正确的结果. 正如MSDN所说: When I execute your program it gives me right result. As MSDN says : If the input cannot be converted to a value of that type, the return value is 0

正如 Shilpi Boosar 所述,输入字符串必须为有效整数,否则结果将为0. 如果您只想接受整数作为输入,则可以使用以下命令: As Shilpi Boosar already said, the input string must be a valid integer, otherwise the result will be 0. If all you want is to accept only integers as input you can use this: int intReturn; if(std::cin >> intReturn) { // We will get here only if the input is valid integer std::cout << intReturn; }

对于从string到int的转换,您还可以使用(作为atoi的替代方法):

For a conversion from string to int you can also use (as an alternative to atoi):

std::string str = "567"; std::istringstream iss(str); int intReturn; if(iss >> intReturn) { // We will get here only if the conversion is successful std::cout << intReturn; }

此处描述了使用stringstreams进行字符串键入和类型转换为字符串的操作. [ ^ ].参见项目: 39.1、39.2和39.3 . :) 如果阅读此项目,您会发现字符串流转换不仅仅是atoi的替代方法.如果提供的 T 支持std::cout << x之类的语法,则可以使用字符串流将任意类型的 T 转换为字符串. :)

Using stringstreams for string to type and type to string conversions is described here[^]. See items: 39.1, 39.2 and 39.3. :) If you read this items you will find out that stringstream conversion is not just an alternative to atoi. Using stringstreams you can convert an arbitrary type T to string if provided T supports syntax like std::cout << x. :)

更多推荐

字符串到int的转换

本文发布于:2023-11-16 03:54:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1600756.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   int

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!