std::getline does not work inside a for-loop

后端 未结 9 2163
醉话见心
醉话见心 2020-12-15 10:28

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

相关标签:
9条回答
  • 2020-12-15 10:42

    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 of ws=cin.get(),will make first character of your string to be in variable ws,instead of just clearing '\n'.

    0 讨论(0)
  • 2020-12-15 10:44

    Are you hitting enter? If not get line will return nothing, as it is waiting for end of line...

    0 讨论(0)
  • 2020-12-15 10:47

    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.

    0 讨论(0)
  • 2020-12-15 10:54

    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 // ...
    
    0 讨论(0)
  • 2020-12-15 10:57
    • Is n properly initialized from input?
    • You don't appear to be doing anything with getline. Is this what you want?
    • getline returns an istream reference. Does the fact that you're dropping it on the ground matter?
    0 讨论(0)
  • 2020-12-15 10:57

    It's quite simple. U jst need to put a cin.get() at the end of the loop.

    0 讨论(0)
提交回复
热议问题