dimanche 3 mai 2015

Why isn't the first input for a string not being assigned to an std::string object?

I wrote a program in which there is a class. In this class there is an overloaded function call operator which takes an std::istream object and std::string object and has a while loop in which we indefinitely take input and concatenate to the std::string parameter.

The problem is that the first input is not being used to be concatenated into the std::string parameter. Although I fixed the problem, I'm unable to understand why is this happening.

This is the complete program:

#include <iostream>
#include <string>
#include <vector>
#include <iterator>

using namespace std;

class PrintString {
public:
 void operator() (istream& is, string &ss) {

   // string s; (1)
    while (is >> ss) {
        ss += ss;
    }

    if (is)
        ss = "";

}
/* 
 * (1): I fixed this by defining another std::string object 
 * and using that to assign to ss. After I did this everything 
 * is working as I wanted it to be.
 */
 };

int main() {

   cout << "enter some words, press ctrl+d to quit\n";
   vector<string> vec;
   PrintString obj;

   string s1;
   s1.clear();
   obj(cin,s1);
   vec.push_back(s1);

   for (const auto &elem: vec)
        cout << elem;

   return 0;
}

The output is this:

enter some words, press ctrl+d to quit
amsndjanjskndna. <- This is the first input
mnmn, <- This is the second input
mnmn,mnmn, <- But in the output the first input is not seen

On my system I'm using Xcode version 6.0.1

Aucun commentaire:

Enregistrer un commentaire