Detecting ENTER key in C++

前端 未结 7 721
不知归路
不知归路 2020-12-17 03:07

I have a program like this,

char name[100];
char age[12];
cout << \"Enter Name: \";
cin >> name;

cout << \"Enter Age: \";
cin >> age         


        
7条回答
  •  囚心锁ツ
    2020-12-17 03:35

    One way to do it is to use getline to read the input, then test the length of the input string. If they only press enter, the length of the line will be 0 since getline ignores newlines by default.

    std::string myString = "";
    
    do {
         std::cout << "Press ENTER to exit" << std::endl;
         std::getline(std::cin, myString);
    } while (myString.length() != 0);
    
    std::cout << "Loop exited." << std::endl;
    

提交回复
热议问题