I\'m trying to collect user\'s input in a string variable that accepts whitespaces for a specified amount of time.
Since the usual cin >> str
does
Declare a character to get in the carriage return after you have typed in the number.char ws;int n;cin>>n;ws=cin.get();
This will solve the problem.
Using
cin>>ws
instead ofws=cin.get()
,will make first character of your string to be in variablews
,instead of just clearing'\n'
.
Are you hitting enter? If not get line will return nothing, as it is waiting for end of line...
You can directly use getline function in string using delimiter as follows:
#include <iostream>
using namespace std;
int main()
{
string str;
getline(cin,str,'#');
getline(cin,str,'#');
}
you can input str as many times as you want but one condition applies here is you need to pass '#'(3rd argument) as delimiter i.e. string will accept input till '#' has been pressed regardless of newline character.
My guess is that you're not reading n
correctly, so it's converting as zero. Since 0 is not less that 0, the loop never executes.
I'd add a bit of instrumentation:
int n;
cin >> n;
std::cerr << "n was read as: " << n << "\n"; // <- added instrumentation
for // ...
It's quite simple. U jst need to put a cin.get() at the end of the loop.