3

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;
}
ilim
  • 4,477
  • 7
  • 27
  • 46
Nadim
  • 47
  • 7
  • 3
    How about [`std::stoi`](http://en.cppreference.com/w/cpp/string/basic_string/stol)? – Some programmer dude Mar 31 '16 at 13:45
  • 1
    I get your confused what this approach is doing but note that it no better than using `cin >> some_variable`. All you have done is made the code more complicated and less efficient. – NathanOliver Mar 31 '16 at 13:45
  • 1
    For your actual problem see: [How to make cin take only numbers](http://stackoverflow.com/questions/10828937/how-to-make-cin-take-only-numbers) – NathanOliver Mar 31 '16 at 13:47
  • @JoachimPileborg Have no idea what that is, just started learning the language, I guess ill look into it after this. – Nadim Mar 31 '16 at 13:48
  • @Nadim Just follow the link. :) – Some programmer dude Mar 31 '16 at 13:50
  • @NathanOliver I'd use cin but when I do the cin.get(); at the end doesn't pause the program as the previous use of cin leaves a new line character in the input stream therefore not pausing the program – Nadim Mar 31 '16 at 13:50
  • 2
    I don't want to count the numbers where MSVC made things needlessly complicated for people simply because the {expletive} console vanishes as soon as the program terminates. @Nadim: `#include `, and `cin.ignore( std::numeric_limits::max(), '\n' );` to flush unread input from `cin` (or any input stream, really). – DevSolar Mar 31 '16 at 13:52
  • @DevSolar Could you explain the (std::numeric_limits::max(), '\n' ) part. Also, whats the difference between what you suggested and just writing cin.ignore(); ? I prefer to fully understand something before I go on and use it :) – Nadim Mar 31 '16 at 14:41
  • @Nadim: Check the [documentation](http://en.cppreference.com/w/cpp/io/basic_istream/ignore) of the functions you're using. `ignore()` has two parameters, the max. number of characters to be ignored, and the delimiter up to which to ignore. Without parameters, you are ignoring exactly one character, which may or may not be a newline depending on the user input. My construct ignores everything up to the next newline. The `numeric_limits<>` template is defined in ``, so you should include that header. – DevSolar Mar 31 '16 at 14:47
  • @DevSolar: Thank you so much for your help, I appreciate it :) – Nadim Mar 31 '16 at 15:03

1 Answers1

1

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)
{
   ....
}
Markus Dheus
  • 576
  • 2
  • 8