Вопрос

I'm looking for a little guidance or help with this particular barrier I'm having in C++. I'm coming from a python background so some of the things are confusing to me. I'm taking a text file as a command line argument and attempting to parse/assign variables to things I've read in the text. I've made a super simple text file, and what I deem to be a super simple cpp file. I did write it based off of some of the other advice similar to questions I saw answered on here.

In python, I could implement a quick regex sort for a .readlines() function and quickly assign variables, and I know it won't be quite that easy in CPP so heres what i've got:

#include <fstream>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    if (argv > 1) 
    {
        std::ifstream s(argv[1]);
        if (s.is_open())
            ; // compiler complained unless this was on its own line
        {
            int i, j, k; // assign ints, no idea why
            s >> i >> j >> k; // 
            std::cout << i << endl;
            std::cout << j << endl;
            std::cout << k << endl;

            // repeat the same with chars, try to assign from file reads?

        }
    }
}

and my text file simply has:

5
3
1

I'm expecting to see output from my program be "5 \n 3 \n 1"

which isnt happening. What I'm looking to eventually do is have a target line like : "Truck 500" and look for "Truck", but assigning an int truck variable to "500"

I'm sorry if my question is all over the place, but any help or references to the right direction are also welcomed. Thanks!

Это было полезно?

Решение

First off, the semicolon after the if-statement is the complete conditional block of the if-statement (and it absolutely can go on the previous line but almost certainly you don't want to have the semicolon in the first place). In addition, you always need to check your input after reading! The stream has no idea what you are going to attempt next and can't predict whether it will be successful before actually trying. That is, your code should look something like this:

std::ifstream in(argv[1]);
if (!in) {
    std::cout << "ERROR: failed to open '" << argv[1] << "' for reading\n";
}
else {
    int i, j, k;
    if (std::cin >> i >> j >> k) {
        std::cout << "read i=" << i << " j=" << j << " k=" << k << '\n';
    }
    else {
        std::cout << "ERROR: there was a format error\n";
    }
}

That said, based on your code you should see the expected output assuming you, indeed, managed to correctly open the file. I'd guess that the code above will point out what's going wrong.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top