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

3

我拿起了一本关于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;
}

3
std::stoi怎么样? - Some programmer dude
1
我知道你对这种方法的作用感到困惑,但请注意,它并不比使用 cin >> some_variable 更好。你所做的只是让代码变得更加复杂和低效。 - NathanOliver
1
请参考您实际的问题:如何让cin仅接受数字 - NathanOliver
@JoachimPileborg 我不知道那是什么,我刚开始学习这种编程语言,我猜我会在此之后调查它。 - Nadim
2
我不想计算那些令人困惑的数字,只因为MSVC控制台在程序终止后立即消失。@Nadim:使用#include <limits>cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );来清除未读取的输入(无论是cin还是任何输入流)。 - DevSolar
显示剩余5条评论
1个回答

1

stringstream 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)
{
   ....
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接