fgets() misses first word

Hi everyone,

I am quite new to c++ so i apologise if this is a simple mistake.

I cannot seem to figure out why my code misses the first word (starts reading from stdin after the first space). There is no bounds checking as i just want to see whats wrong.

Here is the code



#include <iostream>

#include <cstdio>

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
	
	char words[60];
	cin >> words;
	fgets(words, 60, stdin);

	cout << endl;
	cout << words;


	system ("pause");

	return 0;

}

so if i typed in "Steve is a beginner at c++", i would get it all except "steve" and the space just after.

Why is "Steve" missing ?


Any help would be appreciated.
Thank you in advance
Steve


cin >> words; gets the first word from the input stream.
Then fgets(words, 60, stdin); gets the next 59 characters from the stream (or until it hits a newline) and overwrites whatever was already in words with that.

So when you enter "Steve is a beginner at C++", then after the cin >> words; call, words will contain "Steve" and the input stream will contain " is a beginner at C++\n".
Then the fgets call will read the " is a beginner at C++\n" part and store that into words, overwriting everything that was already there.

Try replacing those two lines (both the cin >> words; and the fgets(words, 60, stdin);) with
cin.getline(words, 60);.
You won't need the #include <cstdio> after that.
cin >> words; will read first word in words.
fgets(words, 60, stdin); will read the rest overwriting previous content in words
Thank you long big main and miinipaa for such quick responses to my question. There seems to be a great community on this site. This makes sense now

have a good day both of you
Topic archived. No new replies allowed.