简体   繁体   中英

Why does this code only recognize the first line in the text file? Inputting any number greater than 1 returns "Atomic Number Not Found"

I wanted to make a program that would have a user input a number, and it would search a text file I made on whether or not that number is an atomic number, then pull all the details from the periodic text file and display the info. However, when the user inputs any number greater than 1, it displays atomic number not found.

A solution I have tried is to make a for loop that would continuously go line by line until it finds it, but that did not work, and only made it display "atomic number not found" several times.

#include "pch.h"
#include <string>
#include <iomanip>
#include <iostream>
#include <fstream>
using namespace std;

int main() {
ifstream file_("periodicInfo.txt");
int atomNumReq;
cout << "Please enter atomic number: ";
cin >> atomNumReq;
if (file_.is_open())
{
    string Symbol;
    string Name;
    int atomNum;
    int mass;
    char line;
    while (file_ >> atomNum >> Symbol >> Name >> mass)
    {

        if (atomNumReq == atomNum) {
            cout << atomNum << " " << Symbol << " " << Name << " " << mass << '\n';
        }
        else {
            cout << "Atomic Number Not Found.";
        }

    }
     file_.close();
}
return 0;
}

I expect it to display the line information for the atomic number. I have the text file arranged so that line 1 starts with the number 1, along with the text "1 H Hydrogen 1.01", line 2 of the file being "2 He Helium 4.00", etc all the way until the last atomic number. When the user inputs the number 1, it displays the first line in the text file correctly. When the user inputs any number greater than 1, it displays "Atomic Number Not Found."

1.01 is not an integral value, so file_ >> atomNum >> Symbol >> Name >> mass will read in the 1 into mass but will leave the .01 in the buffer; After that, probably everything is messed up.

Define mass as ...

double mass;

and things should get better.

Further, put the cout << "Atomic Number Not Found."; with some proper condition outside the loop; otherwise you'll get this message for every line that failed before you find the right one.

Fixed it by changing the mass to a double instead of an int. Another problem that showed up was it displaying "Atomic Number Not Found" for all the numbers previous to it. For example, if input was 3, it would display the error twice before displaying the third atomic number. To fix this, I put in a new if statement that solved the problem.

if (atomNumReq != atomNum) continue;

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