Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to number when using getline()

Tags:

c++

I've picked up a book on C++ and I'm basically at the very beginning of it (just started). For some of the problems I had to solve within the book I used the input stream cin the following way -->

cin >> insterVariableNameHere;

But then I did some research and found out the cin can cause a lot of problems, and so found out about the function getline() within the header file sstream.

I'm just having some trouble trying to wrap my head around what's happening in the following code. I don't see anything that uses the extraction operator (>>) to store the number value in. Its (my problem) further explained in the comments I left.

#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;
}
like image 640
Nadim Avatar asked May 16 '26 22:05

Nadim


1 Answers

stringstream myStream(input): Creates a new stream that uses the string in input as "input stream" so to speak.

if(myStream >> nElementIndex) {...): Extracts number from the stringstream created using the line above into nElementIndex and executes ... because the expression returns myStream, which should be non-zero.

You were probably confused by using the extraction as the condition in the if statement. The above should be equivalent to:

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

What you probably wanted was

myStream>>nElementIndex; // extract nElement Index from myStream
if(nElementIndex)
{
   ....
}
like image 89
Markus Dheus Avatar answered May 19 '26 11:05

Markus Dheus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!