bean
bean

Reputation: 337

How to assign variables from colon-separated text file c++

I have a .txt file:

A:One:1:2:15.
B:Two:0:6:5.
C:Three:0:4:6.
D:Four:0:4:8.
E:Five:0:6:2.

And I need to read the file, and assign each value between the (:) to an appropriate variable.

Here is my code so far:

int main()
{
ifstream theFile("Parts.txt");

if(theFile.is_open())
{
    string line;
    while(getline(theFile, line))
    {
        stringstream ss(line);

        string code;
        string partName;
        int minimum;
        int maximum;
        int complexity;

        getline(ss, code, ':');
        getline(ss, partName, ':');
        getline(ss, minimum, ':');
        getline(ss, maximum, ':');
        getline(ss, complexity, ':');
        cout << code << partName << minimum << maximum << complexity << "\n";
    }
}


return 0;
}

Here are the errors I get:

a1.cpp:27:13: error: no matching function for call to 'getline'
        getline(ss, minimum, ':');

a1.cpp:28:13: error: no matching function for call to 'getline'
        getline(ss, maximum, ':');

a1.cpp:29:13: error: no matching function for call to 'getline'
        getline(ss, complexity, ':');

I'm quite new to c++ so any help would be greatly appreciated!

Upvotes: 1

Views: 221

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118330

getline(ss, minimum, ':');

The second parameter to std::getline is always a std::string. minimum is not a std::string. It is an int, this is why this fails to compile. When calling a function in C++ all parameter types must be correct, or convertible (implicitly or by a user-specified conversion operator) to the parameter types that the function expects.

You need to extract this word into a std::string, too, then use the std::stoi library function to convert a std::string into an integer.

Upvotes: 1

Related Questions