【问题标题】:Issue with substr C++substr C++ 的问题
【发布时间】:2015-02-16 04:06:14
【问题描述】:

我正在尝试使用getline 函数从tst.txt 读取一行的程序。但是,当我尝试从中获取子字符串时,我收到一条错误消息,上面写着method substr could not be resolved

我的代码如下。

#include <iostream>
#include <fstream>
#include <string>
#include <istream>
#include <sstream>
#include <stdlib.h>
using namespace std;

int main () {
    string line;
    string substr(int a, int b);
     string name[15];
     int a[15];
     int b[15];
    ifstream myfile ("tst.txt");
    if (myfile.is_open())
    {
        while ( myfile.good() )
        {
            int i;
            getline (myfile,line);
            a[i]= myfile.substr(4,2);
            name[i]= myfile.substr(18,15);
            b[i]= myfile.substr(36,1);
            i=i+1;
            cout << a[i] <<" "<< b[i] << " "<< name[i] << endl;
        }
        myfile.close();
    }
    else cout << "Unable to open file";

    return 0;
}

【问题讨论】:

  • “请尽快帮助”只是乞求投反对票..
  • 作业什么时候交?
  • myfile 是文件流,不是字符串,所以它没有子字符串。你的意思是line.substr()
  • 还有,这里的string substr(int a, int b); 是什么?
  • +i没有初始化,不是说在while里面,就是说i=i+1没有意义……还有其他一些错误

标签: c++ file input substring substr


【解决方案1】:

如上所述,您不能使用std::ifstream 调用substr()。您可能的意思是从读入的line 字符串中取出部分

        a[i]= stoi(line.substr(4,2));
        name[i]= line.substr(18,15);
        b[i]= stoi(line.substr(36,1));

还请注意,您需要将提取的子字符串转换为数字(而不是直接分配它们),因此我添加了stoi()


正如您问题的 cmets 中也提到的,您应该进行更好的错误检查,并正确初始化所有变量。
您的 while() 循环可以简单地重写为

while (getline (myfile,line)) {
    // ...
}

周边if()区块

if (myfile.is_open()) {
    // ...
}

可以省略。

【讨论】:

    【解决方案2】:

    你实际上是在第 行创建一个函数原型:

    string substr(int a, int b);
    

    但永远不要实现它。

    这条线的意义何在? 只需删除它,你永远不会调用这个 substr 函数。您调用的唯一 substr 函数是

    std::ifstream::substr
    

    http://www.cplusplus.com/reference/string/string/substr/

    【讨论】:

    • 他调用的唯一substr 函数是std::ifstream::substr。哪个不存在,他的错误从何而来。
    • @johnkork 感谢您的回复,是的,这是我的错误,我只是在尝试随机的事情来摆脱它。但是我删除了它,仍然是同样的错误。
    猜你喜欢
    • 2019-12-14
    • 2014-09-03
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多