Reputation: 113
I was just writing another program. And used:
while (cin)
words.push_back(s);
words
is a vector
of string
, s
is a string
.
My RAM usage went up after 4 or 5 inputs, SWAP started filling. I am using ubuntu? I just don't see how such simple code could trigger such bad consequences. Or, is something wrong with my system?
EDIT: Complete program:
#include <iostream>
#include <vector>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
int main ()
{
vector<string> words;
string s;
cout << "Enter the string: ";
while (cin)
words.push_back(s);
for (vector<string>::const_iterator iter = words.begin();
iter != words.end(); ++iter)
cout << *iter;
return 0;
}
Upvotes: 0
Views: 734
Reputation: 15872
In your code, you have while (cin)
, which will loop forever. This will lead you to insert a massive number of empty strings into your vector. You are never actually attempting to read anything from the standard input - you basically end up with an infinite loop checking the status of cin
(which will be good until you kill the stream), so you end up trying to allocate a massive amount of space for empty strings.
What you meant to write is:
while (cin >> s)
words.push_back(s);
or
std::copy(std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
std::back_inserter(words));
Side Note: In either case, if you intend to use cin
again at some other point in the program, you will need to clear its error state and flush its buffer.
Upvotes: 1
Reputation:
It is a common bad practice and error to check the state of a stream and not checking the result of an extraction.
Hence, it is:
if(cin >> x) { ... }
else {
// Error
}
for formatted input.
(Please apologize not answering to the ideone post)
Upvotes: 1
Reputation: 1451
Testing for the success of cin or getline is definitely a good practice. Of course, there are structural issues with what you have shown us since I don't see where s is being filled with anything. I would recommend getline over cin for string inputs. It is a lot simpler. These kinds of message boards probably have hundreds of questions about why standard input results in strange behavior. Often, it is the result of not testing for success or not clearing out end of line characters when using cin for both numeric and string inputs. I like the following website for simple questions and answers about in/out streams.
http://www.parashift.com/c++-faq/input-output.html
It is possible that you are seeing memory issues because you have a continuous loop. Since I don't see how the state of the input stream is going to change, you are probably pushing into your vector thousands of times. What is in s? Is it a NULL string, or is what you posted incomplete?
Upvotes: 0