【问题标题】:"No instance of overloaded function 'getline'.." [closed]“没有重载函数'getline'的实例..”[关闭]
【发布时间】:2013-05-13 00:41:54
【问题描述】:

部分代码:

string name;

    cin >> name;

    ifstream userFile( name + ".txt");
    if (userFile.good()){
      // read away
        cout << "Password? \n";

        string pw;

        cin >> pw;

        //checking if pw matches
        getline(userFile, 1);

所以我使用命名空间 std 并包含 sstream 字符串 fstream iostream。 它说参数类型是 (std::ifstream, int) 那么我在这里做错了什么?

编辑: 我认为第二个参数是指您要阅读的那一行。谁能向我解释一下我如何选择我可以以不同方式阅读的行?

【问题讨论】:

  • 您是否包含#include &lt;iostream&gt;#include &lt;string&gt;
  • 1 应该做什么?
  • getline 具有签名 istream&amp; getline (istream&amp; is, string&amp; str);。没有将int 作为第二个参数的重载。
  • umm...读完后你想把这行放在哪里?

标签: c++ getline


【解决方案1】:

引用std::istream::getline,它没有采用ifstream 对象和size_t 的原型。

istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );

同样引用std::getline (string),它有以下内容:

istream& getline (istream& is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);
istream& getline (istream& is, string& str);
istream& getline (istream&& is, string& str);

您以错误的方式使用getline。 如果您尝试使用getline 从文件中读取行,您可以尝试以下操作:

string currLine;
getline(userFile, currLine);
//do something with current line

【讨论】:

  • 由于我对 C++/文件编码很陌生,我该如何解决这个问题?我假设我必须使用类似 getline(myFile, ??) ?
  • @user2376038 我编辑了帖子作为对您评论的回应。
  • 非常感谢!不过我确实有一个问题。这现在是读取整个文件,还是只读取第一行?因为我可能想在这个文件中存储更多信息,而不是用户密码。
  • @user2376038 是的,它会读取一行,你需要一个while循环来逐行读取文件。查看此线程以获得更好的解释:stackoverflow.com/questions/12841931/…
【解决方案2】:

std::getline 具有以下签名:

std::getline

   template< class T, class U, class Allocator >
   std::basic_istream<T, U>& getline(std::basic_istream<T, U>& input,
                                       std::basic_string<T,U, Allocator>& str,
                                       CharT delim);

也就是说,它需要std::istreamstd::string 的实例。此方法用于将流input 的整行消费到缓冲区str 中。

这似乎不是您正在寻找的方法。您说您需要检查userFile 是否与密码匹配。如果那么你应该试试这个:

std::string password;

userFile >> password // insert entire line into password

if (password == "1") // check if password is equal to 1
{
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2013-11-17
    • 1970-01-01
    • 2016-03-16
    • 2014-12-27
    • 1970-01-01
    相关资源
    最近更新 更多