0

Here is my program

    #include <iostream>
using namespace std;

class Student
{
    string name;
public:
    Student(string input)
    {
        name = input;
    }
    Student()
    {
        name = "Unknown";
    }
    void get_name()
    {
        char c;
      
    while (getline(cin, name))
    { 
    for (int i = 0; i < name.length(); i++) {

        c = name.at(i);         

        if (! ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) || c==' ' || c=='\n') ) {

             name = "Unknown";
        }
     }
 }

    }
    void print_name()
    {
        cout << name << endl;
    }
};

int main()
{
        Student name;
        name.get_name();
        name.print_name();
    return 0;
}         

It is accepting input from stdin & working properly but not from the terminal in any way. I can't understand this behavior of the program.

Terminal input not working

https://i.stack.imgur.com/IyLRV.jpg

STDIN input

https://i.stack.imgur.com/Zj6fH.jpg

2 Answers2

0

Change this line:

while (getline(cin, name))

Into

if (getline(cin, name))

May works as you expected. You haven't broken out the loop, so it's always waiting for console input.

Or you can send an EOF in the console, see this question.

Full program:

#include <iostream>
using namespace std;

class Student {
  string name;

 public:
  Student(string input) { name = input; }
  Student() { name = "Unknown"; }
  void get_name() {
    char c;

    if (getline(cin, name)) {
      for (int i = 0; i < name.length(); i++) {
        c = name.at(i);

        if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == ' ' ||
              c == '\n')) {
          name = "Unknown";
        }
      }
    }
  }
  void print_name() { cout << name << endl; }
};

int main() {
  Student name;
  name.get_name();
  name.print_name();
  return 0;
}
prehistoricpenguin
  • 6,130
  • 3
  • 25
  • 42
0
void get_name()
{
    char c;
    getline(cin, name);

    for (int i = 0; i < name.length(); i++)
    {

        c = name.at(i);

        if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == ' ' || c == '\n'))
        {

            name = "Unknown";
        }
    }
    
}

No need for while loop there. If you put while there then it will take input forever. You can use a loop and try breaking it but it won't be efficient.

Client
  • 140
  • 1
  • 6