简体   繁体   中英

C++ 'getline' No instance of overloaded function matches argument list

Trying to use getline but the error keeps saying: No instance of overloaded function matches argument list.

 #include <iomanip>
 #include <string>
 #include <iostream>
 #include <fstream>
 #include <iomanip>

using namespace std;
int main()
{
    int lengthInput;
    int widthInput;
    ifstream fileOpening;
    fileOpening.open("testFile.txt");

while (!fileOpening.eof())
    {
//ERROR ON NEXT TWO LINES OF CODE**
        getline(fileOpening, lengthInput, ' ');
        getline(fileOpening, widthInput, ' ');
    }

    system("pause");
    return 0;

The 2nd parameter of std::getline() expects a std::string to write to, but in both cases you are passing in an int instead. That is why you are getting the error - there really is no version of std::getline() that matches your code.

The second argument of getline is expected to be a reference to a std::string , not a reference to an int .

If you expect that the pair of values can be read from multiple lines, you can use:

while (fileOpening >>  lengthInput >>   widthInput)
{
   // Got the input. Use them.
}

If you expect that the pair of values must be read from each line, you'll have to use a different strategy.

  1. Read lines of text.
  2. Process each line.
std::string line;
while ( fileOpening >> line )
{
   std::istringstream str(line);
   if (str >>  lengthInput >>   widthInput)
   {
      // Got the input. Use them.
   }
}

Important Note

Don't use

while (!fileOpening.eof()) { ... }

See Why is iostream::eof inside a loop condition (ie `while (.stream?eof())`) considered wrong? .

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