0

I'm new to reading input from an input file in C++ and I'm working on taking input from a file that includes two ints in one line. For example, the values in the input file would look something like this:

6 3
12 8
23 78

So far I am able to get each line from the input file but I'm not sure how I can split one line of two values into two ints to use as parameters for one of my functions. I am thinking of using find() to find the position the space character is at. I will get the value after the space character and store it in the int variable rank. But I am unsure how I can use substr() to get the value before the space.

This is the portion of code I have that is getting line-by-line data from the input file and my unfinished attempt at splitting one line into two ints and storing them in two different int variables:

if (argc < 3) // must provide two arguments as input
    {
        throw std::invalid_argument("Usage: ./hello <INPUT FILE> <OUTPUT FILE>"); // throw error
    }

    ifstream input; // stream for input file
    ofstream output; // stream for output file

    input.open(argv[1]); // open input file
    output.open(argv[2]); // open output file

    string command; // to store the next command and operation
    string space = " ";
    string to_find[100] = {};
    int space_pos, length, rank;
        

    while(getline(input,command)) 
    {
      space_pos = command.find(space);
      length = command.substr()
      rank = stoi(command.substr(space_pos + 1));
      words[length]->print(rank);
    }
    input.close();
     output.close();
first last
  • 21
  • 4
  • The easiest way to consume the line: `std::istringstream strm(command); int a; int b; if (strm >> a >> b) { /* safe to use a and b */ } else { /* read error. Notify user*/ }` You might also want to warn the user if there is extra data on the line. [Basically you want option 2 in this answer](https://stackoverflow.com/a/7868998/4581301) – user4581301 Oct 14 '22 at 00:24
  • Take a look at `std::istringstream` to make your life easier. – πάντα ῥεῖ Oct 14 '22 at 00:25
  • Side note: If you change `ifstream input;` to `ifstream input(argv[1]);` you don't need the `input.open(argv[1]);`. Ditto for the outstream. You also don't necessarily need the `input.close();`. [The magic of RAII](https://stackoverflow.com/q/2321511/4581301) takes care of it for you. – user4581301 Oct 14 '22 at 00:29

0 Answers0