本文介绍了字符串到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的转换
发布评论