Reading a full line of input

后端 未结 5 1823
广开言路
广开言路 2020-11-27 06:27

I\'m trying to store the input that user enters through console. so I need to include the \"enter\" and any white space.

But cin stops giving me input a

相关标签:
5条回答
  • 2020-11-27 06:59

    is there a way like readLines till CTRL+Z is pressed or something ??

    Yes, precisely like this, using the free std::getline function (not the istream method of the same name!):

    string line;
    
    while (getline(cin, line)) {
        // do something with the line
    }
    

    This will read lines (including whitespace, but without ending newline) from the input until either the end of input is reached or cin signals an error.

    0 讨论(0)
  • 2020-11-27 07:04
    #include <string>
    #include <iostream>
    
    int main()
    {
    
        std::cout << "enter your name: ";
    
        std::string name;
    
        std::getline(std::cin, name);
    
        return 0;
    
    }
    
    0 讨论(0)
  • 2020-11-27 07:07

    You can use the getline function in c++

    #include<iostream>
    using namespace std;
    int main()
    {
        char msg[100];
        cin.getline(msg,100);
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-27 07:19

    For my program, I wrote the following bit of code that reads every single character of input until ctrl+x is pressed. Here's the code:

    char a;
    string b;
    while (a != 24)
    {
    cin.get(a);
    b=b+a;
    }
    cout << b;
    

    For Ctrl+z, enter this:

    char a;
    string b;
    while (a != 26)
    {
    cin.get(a);
    b=b+a;
    }
    cout << b;
    

    I can't confirm that the ctr+z solution works, as I'm on a UNIX machine, and ctrl+z kills the program. It may or may not work for windows, however; You'd have to see for yourself.

    0 讨论(0)
  • 2020-11-27 07:23
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main() 
        string s;
        while( getline( cin, s ) ) {
           // do something with s
        }
    }
    
    0 讨论(0)
提交回复
热议问题