从txt文件中查找和打印数据

时间:2017-11-05 13:38:46

标签: c++ string std

我有一个字符串类的错误消息。根据我通过尝试解决这个问题找到的例子,我相信我正在使用这个类。

以下是代码:

int main()
{

    string allData, gridNum;

    ifstream gridData;
    gridData.open ("/Users/Neo/Documents/UNi/Year_3/Grid Data Analysis Program/gridData.txt");

    if (gridData.is_open())
    {
        while ( getline (gridData, allData) )
        {


            size_t gridNum = allData.find("Grid Receiver 34");

            string receiverX = allData.substr (gridNum, 40);

            cout << receiverX << endl;


        }
        gridData.close();
    }

    else cout << "Unable to open file..." << endl;


return 0;
}
控制台中的

错误......

libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string
(lldb) 

我试图从文本文件读取到字符串变量。我只想在“Grid receiver 34”之后读出40个字符,然后打印新字符串的内容。

2 个答案:

答案 0 :(得分:2)

    while ( getline (gridData, allData) )
    {


        size_t gridNum = allData.find("Grid Receiver 34");

        string receiverX = allData.substr (gridNum, 40);

        cout << receiverX << endl;


    }

在这里,您逐行阅读文件,搜索&#34;网格接收器34&#34;但是,如果找不到该字符串,则std::string::find将返回std::string::npos。使用它作为substr的参数会让你陷入困境。您应该在使用之前检查它是否已找到:

    while ( getline (gridData, allData) )
    {
        size_t gridNum = allData.find("Grid Receiver 34");
        if(gridNum != std::string::npos)
        {
          string receiverX = allData.substr (gridNum, 40);
          cout << receiverX << endl;
        }

    }

此外,请停止使用using namespace std;

答案 1 :(得分:0)

您可能在找不到搜索字符串的行上遇到异常。

您只想尝试在找到字符串的行上提取子字符串。

修改您的代码,如下所示:

int main()
{
    string allData, gridNum;

    ifstream gridData;
    gridData.open ("/Users/Neo/Documents/UNi/Year_3/Grid Data Analysis Program/gridData.txt");

    if (gridData.is_open())
    {
        while ( getline (gridData, allData) )
        {
            size_t gridNum = allData.find("Grid Receiver 34");
            if (gridNum != std::string::npos)  // add this condition :-)
            {
                string receiverX = allData.substr (gridNum, 40);
                cout << receiverX << endl;
            }
        }
        gridData.close();
    }
    else cout << "Unable to open file..." << endl;

return 0;
}