在C++中把字符串转换为整数的两种简单方法

 更新时间:2022年06月10日 09:45:16   作者:迪鲁宾  
经常会遇到类型转换,本文主要介绍了C++中把字符串转换为整数的两种简单方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

当你用C++编码时,经常会有这样的时候,你会想把一种数据类型转换为另一种。

在这篇文章中,你将看到两种最流行的方法来学习如何在C++中把字符串转换为整数。

让我们开始吧!

C++中的数据类型

C++编程语言有一些内置的数据类型。

  • int,用于整数(整数)(例如10,150)。
  • double,用于浮点数(例如5.0,4.5)。
  • char,用于单个字符(例如'D','!')。
  • string, 一系列的字符(例如 "Hello")。
  • bool,用于布尔值(真或假)。

C++是一种强类型的编程语言,这意味着当你创建一个变量时,你必须明确地声明它将存储什么类型的值。

如何在C++中声明和初始化 int s

要在C++中声明一个int 变量,你需要首先写出该变量的数据类型--本例中是int 。这将让编译器知道该变量可以存储什么类型的值,因此它可以采取什么行动。

接下来,你需要给变量一个名字。

最后,不要忘了用分号来结束语句。

#include <iostream>

int main() {
    int age;
}

然后,你可以给你创建的变量一个值,像这样。

#include <iostream>

int main() {
    int age;
    age = 28;
}

你可以通过初始化变量和最后打印结果来组合这些动作,而不是作为单独的步骤来做。

// a header file that enables the use of functions for outputing information
//e.g. cout or inputing information e.g. cin
#include <iostream> 

// a namespace statement; you won't have to use the std:: prefix
using namespace std;


int main() { // start of main function of the program
    int age = 28; 
    // initialize a variable. 
    //Initializing  is providing the type,name and value of the varibale in one go.

    // output to the console: "My age is 28",using chaining, <<
    cout << "My age is: " << age << endl;
}// end the main function

如何在C++中声明和初始化 string s

字符串是单个字符的集合。

在C++中声明字符串的工作方式与声明和初始化ints非常相似,你在上面的章节中看到了这一点。

C++标准库提供了一个string 类。为了使用字符串数据类型,你必须在文件的顶部,在#include <iostream> 之后,包括<string> 头部库。

在包括该头文件之后,你还可以添加你之前看到的using namespace std;

在其他方面,加入这一行后,你在创建字符串变量时将不必使用std::string ,只需使用string

#include <iostream>
#include <string>
using namespace std;

int main() {
    //declare a string variable

    string greeting;
    greeting = "Hello";
    //the `=` is the assignment operator,assigning the value to the variable

}

或者你可以初始化一个字符串变量并将其打印到控制台。

#include <iostream>
#include <string>
using namespace std;

int main() {
    //initialize a string variable

    string greeting = "Hello";
   
   //output "Hello" to the console
   cout << greeting << endl;
}

如前所述,C++是一种强类型的语言。

如果你试图给出一个与数据类型不一致的值,你会得到一个错误。

另外,将字符串转换为整数并不像使用类型转换那样简单,你可以在将doubles转换为ints时使用。

例如,你不能这样做。

#include <iostream>
#include <string>
using namespace std;

int main() {
   string str = "7";
   int num;

   num = (int) str;
}

编译后的错误将是。

hellp.cpp:9:10: error: no matching conversion for C-style cast from 'std::__1::string' (aka
      'basic_string<char, char_traits<char>, allocator<char> >') to 'int'
   num = (int) str;
         ^~~~~~~~~
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/string:875:5: note: candidate function
    operator __self_view() const _NOEXCEPT { return __self_view(data(), size()); }
    ^
1 error generated.

有几种方法可以将字符串转换为int,你会在后面的章节中看到其中两种方法。

如何使用 stoi() 函数将字符串转换为int

将字符串对象转换为数字int的一个有效方法是使用stoi() 函数。

这种方法通常用于较新版本的C++,在C++11中被引入。

它将一个字符串值作为输入,并将它的整数版本作为输出返回。

#include <iostream>
#include <string>
using namespace std;

int main() {
   // a string variable named str
   string str = "7";
   //print to the console
   cout << "I am a string " << str << endl;

   //convert the string str variable to have an int value
   //place the new value in a new variable that holds int values, named num
   int num = stoi(str);
   
   //print to the console
   cout << "I am an int " << num << endl;
}

输出。

I am a string 7
I am an int 7

如何使用stringstream 类将一个字符串转换为一个int

stringstream 类主要用于早期版本的C++。它通过对字符串进行输入和输出来工作。

要使用它,你首先要在你的程序顶部加入sstream 库,加入一行#include <sstream>

然后你添加stringstream ,并创建一个stringstream 对象,该对象将保存你要转换为int的字符串的值,并在转换为int的过程中使用。

你使用<< 操作符,从字符串变量中提取字符串。

最后,你使用>> 操作符将新转换的int值输入到int变量中。

#include <iostream>
#include <string>
#include <sstream> // this will allow you to use stringstream in your program

using namespace std;

int main() {
    //create a stringstream object, to input/output strings
   stringstream ss; 
   
   // a variable named str, that is of string data type
   string str = "7";
   
   // a variable named num, that is of int data type
   int num;
   
   
   //extract the string from the str variable (input the string in the stream)
   ss << str;
   
   // place the converted value to the int variable
   ss >> num;
   
   //print to the consloe
   cout << num << endl; // prints the intiger value 7
}

总结

这就是你的成果!你已经看到了在C++中把字符串转换为整数的两种简单方法。

到此这篇关于在C++中把字符串转换为整数的两种简单方法的文章就介绍到这了,更多相关C++ 字符串转换为整数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • C语言构建动态数组完整实例

    C语言构建动态数组完整实例

    这篇文章主要介绍了C语言构建动态数组完整实例,帮助读者加深对C语言数组及指针的理解,需要的朋友可以参考下
    2014-07-07
  • C语言数据存储详解

    C语言数据存储详解

    在本篇文章里小编给大家整理的是关C语言数据存储,小编觉得这篇文章写的很不错,有需要的朋友们可以学习参考下,希望能够给你带来帮助
    2021-10-10
  • C++使struct对象拥有可变大小的数组(详解)

    C++使struct对象拥有可变大小的数组(详解)

    下面小编就为大家带来一篇C++使struct对象拥有可变大小的数组(详解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-12-12
  • C语言二叉树常见操作详解【前序,中序,后序,层次遍历及非递归查找,统计个数,比较,求深度】

    C语言二叉树常见操作详解【前序,中序,后序,层次遍历及非递归查找,统计个数,比较,求深度】

    这篇文章主要介绍了C语言二叉树常见操作,结合实例形式详细分析了基于C语言的二叉树前序,中序,后序,层次遍历及非递归查找,统计个数,比较,求深度等相关操作技巧与注意事项,需要的朋友可以参考下
    2018-04-04
  • C++11中std::async的使用详解

    C++11中std::async的使用详解

    这篇文章主要介绍了C++11中std::async的使用详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-02-02
  • C++解析wav文件方法介绍

    C++解析wav文件方法介绍

    最近将项目改为跨平台,于是音频模块从微软的XAudio2改用OpenAL库。之前使用MSDN的代码,所以现在改为了C++标准的写法,适用性更广
    2022-09-09
  • C++学习笔记之类成员指针

    C++学习笔记之类成员指针

    类成员指针时指可以指向类的非静态成员的指针,下面这篇文章主要给大家介绍了关于C++类成员指针的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-04-04
  • linux c多线程编程实例代码

    linux c多线程编程实例代码

    这篇文章主要介绍了linux系统中的c多线程编程实例,大家可以参考使用以下代码
    2013-11-11
  • 一篇文章带你了解C++智能指针详解

    一篇文章带你了解C++智能指针详解

    这篇文章主要介绍了c++ 智能指针基础的相关资料,帮助大家更好的理解和学习使用c++,感兴趣的朋友可以了解下,希望能给你带来帮助
    2021-08-08
  • 基于C语言实现猜数字游戏

    基于C语言实现猜数字游戏

    这篇文章主要为大家详细介绍了基于C语言实现猜数字游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-05-05

最新评论