使用getline()时将字符串转换为数字

Converting string to number when using getline()

本文关键字:字符串 转换 数字 getline 使用      更新时间:2023-10-16

我读了一本关于C++的书,我基本上处于它的最开始(刚刚开始)。对于我在书中必须解决的一些问题,我使用输入流cin的方式如下-->

cin >> insterVariableNameHere;

但后来我做了一些研究,发现cin会引起很多问题,所以我发现了头文件sstream中的函数getline()。

我只是在试图理解以下代码中发生的事情时遇到了一些麻烦。我没有看到任何使用提取运算符(>>)来存储数值的东西。这(我的问题)在我留下的评论中得到了进一步解释。

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
// Program that allows a user to change the value stored in an element in an array
int main() 
{
    string input = "";
    const int ARRAY_LENGTH = 5;
    int MyNumbers[ARRAY_LENGTH] = { 0 };
    // WHERE THE CONFUSION STARTS
    cout << "Enter index of the element to be changed: ";
    int nElementIndex = 0;
    while (true) {
        getline(cin, input); // Okay so here its extracting data from the input stream cin and storing it in input
        stringstream myStream(input); // I have no idea whats happening here, probably where it converts string to number
        if (myStream >> nElementIndex) // In no preceding line does it actually extract anything from input and store it in nElementIndex ? 
         break; // Stops the loop
        cout << "Invalid number, try again" << endl;
    }
    // WHERE THE CONFUSION ENDS
    cout << "Enter new value for element " << nElementIndex + 1 << " at index " << nElementIndex << ":";
    cin >> MyNumbers[nElementIndex];
    cout << "nThe new value for element " << nElementIndex + 1 << " is " << MyNumbers[nElementIndex] << "n";
    cin.get();
    return 0;
}

字符串流myStream(input):创建一个新的流,可以说,该流使用输入中的字符串作为"输入流"。

if(myStream>>nElementIndex){…):将使用上面一行创建的字符串流中的数字提取到nElementIndex中并执行…,因为表达式返回的myStream应为非零。

如果在if语句中使用提取作为条件,您可能会感到困惑。以上应等同于:

myStream>>nElementIndex; // extract nElement Index from myStream
if(myStream)
{
   ....
}

你可能想要的是

myStream>>nElementIndex; // extract nElement Index from myStream
if(nElementIndex)
{
   ....
}