目录
  • C++中的数据类型
  • 如何在C++中声明和初始化 int s
  • 如何在C++中声明和初始化 string s
    • 如何使用 stoi() 函数将字符串转换为int
    • 如何使用stringstream 类将一个字符串转换为一个int
  • 总结

    当你用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++中把字符串转换为整数的两种简单方法。

    声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。