简体   繁体   中英

How do I read only one type from a single-line file with multiple types?

So I have a text file with a single line that looks like this:

Steve 3 Sylvia 7 Craig 14 Lisa 14 Brian 4 Charlotte 9 Jordan 6

What I'm attempting to do is read each integer from the text file. I've tried some code which looks like this

#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;

    int main()
    {
        int a;

        ifstream inStream;
        inStream.open("file.txt");

// case for file open failing
        if ( inStream.fail() )
        {
            cout << "File open failed.\n";
            exit(1);
            }

//attempting to read each integer and print it to see if it worked right
            while( inStream.good() )
            {
                inStream>>a;
                    cout<<a;

             }


         return 0;
     }

I know this is pretty simple to do when the whole file consists of just integers, or if the entire file wasn't one line, however I'm having trouble with this case

If you know that the format will be like name number name number ... then you can do something like this:

int a;
string name;
// read name first then number
while( inStream >> name >> a )
{
    cout << a << endl;
}

You can't jump over the names while reading with >> , but you can read them and do nothing with them.

A basic regex search can easly solve the problem

#include <iostream>
#include <regex>
#include <string>

int main(int argc, const char** argv) {
  std::string buf = "Steve 3 Sylvya 7 Craig 14 Lisa 14 Brian 4 Charlotte 9 Jordan 6";
  std::regex all_digit("\\d+");
  std::smatch taken;
  while(std::regex_search(buf, taken, all_digit, std::regex_constants::match_any)) {
    for(auto x : taken)
      std::cout << x << '\n';
    buf = taken.suffix().str();
  }

  return 0;
}

Please adapt the above code to your needs. Switch the string with the buffer taken from the file.

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