简体   繁体   中英

c++ not validating string input

int main() {
    Population town;
    int population;
    int numBirths, numDeaths;
    string city, intTest;
    bool isValid = true;

    do {
        cout << "Enter name of city: ";
        getline(cin, city);
        for (int i = 0; i < city.length(); i++) {
            if (!isalpha(city[i])) {
                isValid = false;
                break;
            }
        }
    } while(!isValid);

Its not properly checking to see if the input is a string or not. Not sure whats wrong with the code.

if (!(isalpha(city[i]))) {
   isValid = false;
}
else {
    isValid = true;
    break;
}

The first time this loop finds an alphabetic character, it will set isValid to true and then break out of the loop. As your code stands, isValid is true if there is any alphabetic character in the string and false otherwise after the loop.

You probably actually want something like:

string city; //populate this
bool isValid = true; //Innocent till proven guilty

do {
    city = ... ; //get new city
    isValid = true; //Don't forget to reset!!
    for (int i = 0; i < city.length(); i++) {
        if(!isalpha(city[i])) {
            isValid = false;
            break; //If we're invalid, doesn't matter what the rest is
        }
    }
while(!isValid);

Furthermore, for whatever reason, you're reading into city twice.

First you read a single word:

cin >> city;

and then you read a full line:

getline(cin, city);

If the city will only be a single word, use the first and delete the second. Otherwise, if the city will be multiple words (that the user will enter terminated by a newline (enter key)), delete the first and use the second.

You are using two lines for reading into city .

    cin >> city;
    getline(cin, city);

You need only one of them.

If the name of a city does not contain spaces in them, for your application, use the first one. Otherwise, use the second one. Don't use both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM