Valid input checking

Hello I am trying to write a program that will check the input to make sure what the user entered is an integer only. This is it basically, how would I make it check that the value was an integer, and if not, keep asking until the value is an integer.

1
2
3
4
5
6
7
8
9
10
int input = 0;
cout << "Please enter the number << endl;
cin >> input;

while(input < 0 || input != an integer)
{
  cout << "Incorrect value or negative, please try again." << endl;
  cout << "Please enter the number << endl;
  cin >> input;
}


I know repeating the output is somewhat bad, but thats the only way I know how to do it currently. Thank you in advanced.
You can do something like this:
1
2
3
4
5
6
7
8
9
10
#include <limits>
// ...
int input;
std::cout << "Enter a number: ";
while (!(std::cin >> input) || input < 0)
{
    std::cout << "Invalid or negative value, try again: ";
    std::cin.clear(); // Clear error flags
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

Basically, if the user enters something that's not an integer, the input will fail and cin will go into an error state (which is what we check for in our while loop).
Before we can attempt to get input again, we need to clear the error flags (line 8) and discard everything the user inputted (line 9).
Awesome thank you! What about if I want to make sure the value is the correct string? Like
1
2
3
4
5
6
7
cout << "Do you want to enter a new value?" << endl;
cin >> answer;

if(answer != "YES" || answer != "yes" || answer != "Yes")
{
    cout << "Please enter the correct value" << endl;
}


Something like this. Thanks again in advance
In that example, it might be better if the user only has to enter 'y' (for yes) or 'n' (for no) rather than "yes" or "no".
But for other cases (and even this one, if you really want to), you can do something like
1
2
3
4
5
6
7
8
9
10
std::cout << "Enter a word: ";
std::string answer;
// Convert all characters to lowercase -- requires #include <cctype>
for (char& ch : answer)
    ch = std::tolower(ch);
// Or, if you have an older compiler:
/* for (unsigned i = 0; i < answer.size(); ++i)
      answer[i] = std::tolower(answer[i]); */
if (answer == "hello")
    std::cout << "Hi!";
which basically just converts all characters to lowercase first before comparing it with another string.
How does this check that the value is correct on yes or no? OR 'y' or 'n'?
Err...whoops, I might have (very slightly) misread your question.

You could take the general idea of my last post and just loop it:
1
2
3
4
5
6
7
8
9
10
11
std::string answer;
std::cout << "Enter \"yes\" or \"no\": ";
while (true)
{
    std::cin >> answer;
    for (char& ch : answer) ch = std::tolower(ch);
    if (answer != "yes" && answer != "no")
        std::cout << "Invalid input, try again: ";
    else
        break;
}
or something similar to that.
Ah okay this looks better lol thank you
So I have another questions. I am checking the valid input so far, at the end of my code I ask if they want to save the file as a new file. How would a make sure to check that that file does not already exist? Also if they want to modify or read the file, how do I check and throw an error if the file does not exist that they want to read, or modify?
Hmm, for checking whether a file exists or not, you could try to open it in read-only mode and see if that works or not:
1
2
3
4
5
std::ifstream readFile("file name goes here");
if (!readFile)
    // File doesn't exist, or if it does, it can't be read
else
    // File exists (since we have a valid input stream) 


Note that if you use std::ofstream to write to a file that doesn't exist, then the file will be created automatically.
Awesome thank you, 1 more question. How do I modify my program to accept a filename that the user inputs right now it hard codes "example.txt" as a the filename and I am having a hard to getting it to accept user input on this
You can just use a std::string, like for anything else:
1
2
3
4
5
6
7
8
9
std::string filename;
std::cout << "Enter a file name: ";
std::getline(std::cin, filename);

// If your compiler supports C++11, this should work:
std::ifstream readFile(filename); // Same idea for (o)fstream

// Otherwise, if that doesn't work, this should:
std::ifstream readFile(filename.c_str());
Yeah but when i do it, for some reason it is not recognizing it in the class. Like ifstream throws an error no matching function for call to std::basic_fstream<char>::basic_fstream(std::string&)'

here is my code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

class myClass{
    public:
    myClass (string fname)  //constructor
    {
        filename = fname;
        selection = 0;
        input = 0;
        number = 0.0;
        anothernumber = 0.0;
        replacement = 0.0;
        newfilename = "";
        choice = "";
        answer = "";
    }

    string returnNewfile()
    {
        return newfilename;
    }

    string returnAnswer()
    {
        return answer;
    }

    int returnSelection()
    {
        return selection;
    }

    int returnInput()
    {
        return input;
    }

    double returnOtherNumber()
    {
        return anothernumber;
    }

    double returnNumber()
    {
        return number;
    }

    double returnReplace()
    {
        return replacement;
    }

    string returnChoice()         //choice
    {
        return choice;
    }

    void Select()
    {
    cout << "Please enter 0 for read or 1 for write mode" << endl;
    while (!(cin >> selection) || selection < 0)
    {
        cout << "Value is invalid, try again." << endl;
        cin.clear(); //Clear error flag
        cin.ignore();
    } // end while

        if (selection == 0)
        {
            ifstream filename ("example.txt");
            if (filename.is_open())
            {
                while(getline(filename, line))                 //Goes through the file and gets each line individually
                {                                             //and prints out whats in it line by line.
                    cout << '\n' <<"This is what is in the file: " << line << endl;
                }
            filename.close();
            }
        }
        else if (selection == 1)
        {
            fstream filename("example.txt");
            if (filename.is_open())
                {
                    cout << "How many numbers do you want to enter? " << endl;

                    while (!(cin >> input) || input < 0)
                    {
                        cout << "Value is invalid, try again." << endl;
                        cin.clear(); //Clear error flag
                        cin.ignore();
                    } // end while
                 for (int i = 1; i <= input; i++)              //This will check how many numbers you want to enter
                 {                                             //then will keep asking for the numbers until it reaches what you wanted.

                    cout << '\n' << "This is what is in the file: " << line << endl;
                    cout << '\n' << "Hit a to accept value, r to replace, d to delete it, or type x to accept rest of the values. " << endl;

                    while (!(cin >> choice))
                    {
                        cout << "Value is invalid, try again." << endl;
                        cin.clear(); //Clear error flag
                        cin.ignore();
                    } // end while

                    if (choice == "a" || choice == "A")
                    {
                        filename << line << endl;
                    }

                    if (choice == "r" || choice == "R")
                    {
                        cout << "What number do you want to replace it with? " << endl;

                        while (!(cin >> number) || number < 0)
                        {
                            cout << "Value is invalid, try again." << endl;
                            cin.clear(); //Clear error flag
                            cin.ignore();
                        } // end while
                        filename << number << " " << line << endl;
                        cout << "The number has been replaced."  << endl;
                    }

                    if (choice == "d" || choice == "D")
                    {
                        number--;
                        cout << "Number deleted." << endl;
                    }

                    if (choice == "x" || choice == "X")
                    {
                        terminate();
                    }
                        cout <<'\n' << "Would you like to enter a new number? y or n" << endl;
                        cin >> answer;

                    if (answer == "y" || answer == "Y")
                    {
                        cout << '\n' << "Please enter the number." << endl;

                        while (!(cin >> anothernumber) || anothernumber < 0)
                        {
                            cout << "Value is invalid, try again." << endl;
                            cin.clear(); //Clear error flag
                            cin.ignore();
                        } // end while
                        filename << line << " ";
                        filename << anothernumber << endl;
                    }
                }// end of for loop
            cout << "Would you like to save the changes of the file to a new one?" << endl;
            cin >> newfilename;
            while (newfilename != "yes" || newfilename != "Yes" || newfilename != "YES" )
            {
                cout << "Value is invalid, try again." << endl;
                cin.clear(); //Clear error flag
                cin.ignore();
            } // end while

                if(newfilename == "yes" || newfilename == "Yes" || newfilename == "YES")
                {
                    string thisfilenow;
                    cout << "Please enter new file name." << endl;
                    cin >> thisfilenow;   //this will save the new data into another file leaving the old file intact.
                    filename << thisfilenow;
                }
              // while loop
            }// end of filename.open if statement
             filename.close();
        }// end of else if selectio == 1
    }//End of void select

    private:
    string filename;
    string line;
    string answer;
    string newfilename;
    int selection;
    double myarray[10][10];
    int input;
    double number, replacement,anothernumber;
    string choice;
};
int main()
{
    string fname = "example.txt";

    myClass co(fname);
    co.Select();
} 
Last edited on
Did you try the second one?
std::ifstream readFile(filename.c_str()); // Same idea for ofstream or fstream
Sweet that worked I forgot about the c_str() thats what happens when you stop coding.. LOL Thank you! So how would reconfigure my program to accept a file I enter instead of hardcoding the file name "example.txt" as you can see on line 74 and 86. I have messed with it a little but no luck ended up messing it up more than fixing it.
Topic archived. No new replies allowed.