简体   繁体   中英

Use getline to split a string and check for int

I have a file:

name1 8
name2 27
name3 6

and I'm parsing it into vector. This is my code:

  int i=0;
  vector<Student> stud;

  string line;
  ifstream myfile1(myfile);
  if (!myfile1.is_open()) {return false;}
  else {
    while( getline(myfile1, line) ) {
      istringstream iss(line);
      stud.push_back(Student());
      iss >> stud[i].Name >> stud[i].Grade1;
      i++;
    }
    myfile1.close();
  }

I need to check if the stud[i].Grade1 is int. If it isn't it return false. File can contain:

name1 haha
name2 27
name3 6

How can I do it?

EDIT:

I have tried another way (without getline) and it seems to work. I don't understand why :/

int i=0;
vector<Student> stud;

ifstream myfile1(myfile);
if (!myfile1.is_open()) {return false;}
else {
  stud.push_back(Student());
  while( myfile1 >> stud[i].Name ) {
    if(!(myfile1 >> stud[i].Points1)) return false;
    i++;
    stud.push_back(Student());
}
myfile1.close();
}

If type of Grade1 in numerical such as int , Use std::istringstream::fail() :

// ...
    while( getline(myfile1, line) ) {
      istringstream iss(line);
      stud.push_back(Student());
      iss >> stud[i].Name;
      iss >> stud[i].Grade1;
      if (iss.fail())
        return false;
      i++;
    }
    myfile1.close();
  }
// ...

It could look like this:

std::vector<Student> students;
std::ifstream myfile1(myfile);
if (!myfile1.is_open())
    return false;

std::string line;
while (std::getline(myfile1, line))
{
    // skip empty lines:
    if (line.empty()) continue;

    Student s;
    std::istringstream iss(line);
    if (!(iss >> s.Name))
        return false;
    if (!(iss >> s.Grade1))
        return false;

    students.push_back(s);
}

just note that iss >> s.Grade1 will succeed not only for decimal, but also for octal and hexadecimal numbers too. To make sure that only decimal value will be read, you could read it into the temporary std::string object and validate it before you use it to retrieve the number. Have a look at How to determine if a string is a number with C++?

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