I tried to make a restriction input which restricts letters and spaces only on setx() and numbers between 100 and 200 only on sety().
While I need to use getline() to make sure it reads completely including spaces or in case spaces with 2 or more words, suddenly it ignores the getline completely and skipped to sety() instead.
Keep in mind the c++ language should be beginners and dont make it complicated so I can read it easy as a beginner
#include <iostream>
#include <string>
#include <cctype>
usingnamespace std;
class Insert
{
private:
string x;
int y;
public:
void setx();
void getx();
void sety();
void gety();
};
void Insert::setx()
{
bool good {};
do {
std::cout << "Enter letter or words: ";
std::getline(std::cin, x);
good = true;
for (constauto& ch : x)
if (!std::isalpha(static_cast<unsignedchar>(ch)) && !std::isspace(static_cast<unsignedchar>(ch))) {
good = false;
break;
}
} while (!good && (std::cout << "Error\n"));
}
void Insert::getx()
{
std::cout << "You typed " << x << "\n";
}
void Insert::sety()
{
cout << "Enter 100 to 200" << endl;
cin >> y; //input for the set function
while (y < 100 || y > 200) //loops again if the input was invalid that the number is less than 100 or more than 200, the while statement will loop again until you get the correct input.
{
cout << "Error\n";
cout << "Enter around 100 to 200" << endl;
cin >> y;
}
}
void Insert::gety()
{
cout << "Your number is " << y << "\n"; //output of the get function will appear the value of the input variable if the input was valid
}
int main()
{
Insert records[3];
int inputnumber;
cout << "Enter number of words and numbers ";
cin >> inputnumber;
if (inputnumber > 3)
{
cout << "Value has reached to over 3" << endl;
}
else
{
for (int i = 0; i < inputnumber; i++)
{
cout << "total" << i + 1 << " : " << endl;
records[i].setx();
records[i].sety();
}
cout << "\nTotal stuff you have inputed : " << endl;
for (int i = 0; i < inputnumber; i++)
{
records[i].getx();
records[i].gety();
}
}
return 0;
}
After you cin >>, the user inputs something. They "submit" the input by pressing the enter key. The enter key puts a NEWLINE character in the buffer, cin ignores it and it stays in the buffer.
Getline tries to read, finds the newline character in the buffer, thinks the user has finished inputting their data.
So after cin >>, put cin.ignore() to get rid of the newline character.
@sapshe
The problem is I need to restrict the input by spaces and letters only.
If I just use cin >> entername, it will only works on one word and only read one word like for example if my input was typed "Hello there" then it will result the output only reads "Hello".
Therefore I must use getline so it can read more than 2 words
Yeah next time just tell me which line specifically if you want to point out something on the code so I can know where is the exact code that needs to be changed