0

Code:

std::istringstream ss(argv[2]);

ss >> blocks;

if (ss.fail() || 0 >= blocks) {
    usage("Second parameter: must be a number,""and greater than zero"); // my custom method
    return 1;
}

Here the line : ss>>blocks; Can anyone please specify its working. Isn't ss is the object, how come we are using it like this, aren't we supposed to use '.' to get the class variables or methods.

I am new to C++, cam from Java, so it's bit hard to get.

I have defined variable blocks as 1 as its initialized value. But it changes using ss >> blocks. I want to know the working of this line.

I understood below lines:

std::istringstream ss(argv[2]); // we are passing argument to constructor 

ss >> blocks; // unable to get

ss.fail() // fail is the method in istringstream class which we are accessing using ss object.
Chinmay
  • 11
  • 2
  • `>>` is an overloaded operator for `std::istream` and all derivates. – πάντα ῥεῖ May 16 '23 at 05:08
  • You don't have to use stringstream, you can also use [std::stoi](https://en.cppreference.com/w/cpp/string/basic_string/stol). You might need to add some exception handling in case of failures. – Pepijn Kramer May 16 '23 at 05:08
  • `cin` and `cout` are also objects. There is a list of good books [here](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282). (You have a lot to unlearn from Java.) – molbdnilo May 16 '23 at 08:46

2 Answers2

1

You said

Aren't we supposed to use . to get class variables or methods?

This is perfectly legal Java

string s = "hello ";
s += "john"; 

In Java the += operator has be overloaded so that it works on strings. It's a similar case here >> has been overloaded so that it works on streams.

In C++ the notation A op x, where A is an object, op is some operator and x is some value, can be used either to call a global function of two arguments, or a method of A with one argument. As it happens, in this case, it's the latter. That method results in an integer value being read from the stream and assigned to the passed integer variable.

john
  • 85,011
  • 4
  • 57
  • 81
0

In C++, << and >> are left and right shift operators, respectively. These operators are overloaded with streams to represent serialization and deserialization.

ss >> blocks will stream a number in blocks until a white space is encountered.

See: Processing strings using std::istringstream

theSlyest
  • 429
  • 1
  • 6
  • 16