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

标签 c++

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

最佳答案

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

关于c++ - 使用 getline() 时将字符串转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36335117/

相关文章:

c++ - 从 C 数组初始化 std::array 的正确方法

C++ 防止复制成员数据

c++ - 如何为结构体数组分配内存?

c++ - 如何将整数 vector 插入 std::map 的键、值

c++ - 如何让每个子进程获得不同的客户端地址(UDP SOCKET)?

c++ - 如何制作一个简单的 C++ Makefile

c++ - #include inside 函数体不起作用 (CDT/Eclipse C++)

c++ - 尝试定义从抽象类派生的类类型的对象时出错

c++ - 限制套接字的最大速度

c++ - 如何在手动编码时以直接的方式检测模板函数的适当返回类型