getline() a string giving difficulty

前端 未结 3 556
逝去的感伤
逝去的感伤 2020-12-22 13:00

i am doing a task where i am inputting ist no of times you want to have input and then i am inputting a full line by the use of getline but sime how i am not able to do that

相关标签:
3条回答
  • 2020-12-22 13:37

    You are mixing formatted input and unformatted input functions.

    operator>> leaves the trailing newline after the number you extracted in the input buffer, but this isn't a problem for subsequent reads done with operator>> because it skips all the whitespace it finds before reading. On the other hand, getline reads until it finds the delimiter (\n by default) without skipping anything.

    Long story short: if you want to use getline you have to clean the buffer from the \n after your cin>>test;:

    #include <limits>
    // ...
    
    cin>>test;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    
    0 讨论(0)
  • 2020-12-22 13:37

    I believe your problem is you are giving input stream as a parameter where you should give buffer. Try this.

    {  
        char szInput[256];  
        cin.getline( szInput,256);  
        len = strlen(szInput);  
        cout<<len;  
    }
    
    0 讨论(0)
  • 2020-12-22 13:54
    for(j=1;j<=test;j++)     
    {          
    getline( cin,s);         
    len = s.length();         
    cout<<len;      
    } 
    

    This is reading in the int and the string with the one carridge return.

    It reads 1 as the total and then nothing as the string (hence the length of 0). Try 1TEST and this should give you a length of 4.

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