Been pullin my hair trying to figure what's causing this. Basically, got a for loop capturing user input using getline, and putting it into a string array.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
int i, n;
string mystr;
stringstream ss;
string * testdata;
In a nutshell, the array position 0 appears to get bypassed on the intial user entry, going into array position 1 instead.
The newline that you entered after entering the number of entries remains in the stream after the call to cin >> i. After that line, you should call cin.sync(); which syncs up the stream with the input, i.e. the newline is ignored.
I also have an output which i can't seem to grasp (0= 01= 012= )
The call to ss.clear(); does not clear the contents of the stringstream, it just clears the error state. So, since your stringstream isn't local to the for loop, the numbers just keep getting appended to the stream. Making the stringstream local to the for loop will solve this problem. Of course, you could just do cout << n as well.
Another way to get rid of the newline form the input buffer is to use cin.ignore();
The stringstream can be emptied by assigning an empty string ss.str(""); though it looks like the program could work just as well without any stringsteam at all.
... but i'm sure that was just tricking the system.
The cin.sync() in that same line did not fix it.
The cin.ignore() however did.
The ss.str("") also did the trick.
Yes, i could have just outputted the n value to get the correct output, but the fun here is trying to figure out why something doesn't work to better understand how it works.
... but i'm sure that was just tricking the system.
That comment indicates a vague understanding of the situation.
After the cin >> i; there is a newline character '\n' in the input buffer. There are various ways to remove that character. cin.get(); will do the job.
cin.ignore(); will also do it, but the intention is more clear to the reader - and writing code which is intelligible to the human reader is in practice at least as important, if not more so, than writing code which the computer can understand.
The ignore statement can also be expanded, in case there were any extraneous characters apart from the newline, in order to ignore everything up to and including the next newline character.
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
ot maybe easier to understand for a beginner,
cin.ignore(100, '\n' ); which will ignore up to 100 characters,or until the '\n' character is read.
Thanks for the clarification.
Understanding what each method and function does within classes is all part of the learning curve.
I'm not very high up in that curve yet :-)