c++ - 如何使用getline从文件中读入数组

标签 c++ arrays file-io

在这个问题上我需要你的帮助。我有一个包含这个的文件:

1x+1y+1z=5
2x+3y+5z=8
4x+0y+5z=2

我必须将它存储到一个字符串中。一旦存储,输出应该是这样的:

1x+1y+1z=5
a=1 b=1 c=1 d=5
2x+3y+5z=8
a=2 b=3 c=5 d=8
4x+0y+5z=2
a=4 b=0 c=5 d=2

这是我的代码,但是它没有输出任何东西。有谁能够帮助我?它在第 19 行给我一个错误,但我不知道如何修复它。错误指出“没有匹配的调用函数。”

|19|error: no matching function for call to 'std::basic_ifstream::getline(std::string [10], int)'| |22|error: no matching function for call to 'std::basic_istringstream::basic_istringstream(std::string [10])'|

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    ifstream file("matrix.txt");

    if (!file)
    {
        cout << "Could not open input file\n";
        return 1;
    }


    for (string line[10]; file.getline(line, 10); )
    {
        cout << line << '\n';
        istringstream ss(line);

        double a, b, c, d;
        char x, y, z, eq;

        if (ss >> a >> x >> b >> y >> c >> z >> eq >> d)
        {
            if (x == 'x' && y == 'y' && z == 'z' && eq == '=')
            {
                cout << "a = " << a
                     << "  b = " << b
                     << "  c = " << c
                     << "  d = " << d << '\n';
            }
            else
            {
                cout << "parse error 2\n";
            }
        }
        else
        {
            cout << "parse error 1\n";
        }

    }

}

最佳答案

有几个错误。

错误编号。 1

您不能也不应该声明 string line[10]。您也不应该使用 for 循环。这是从流中逐个字符串读取字符串的经典实现:

string line;
while (file >> line) {
  ... // do stuff
}

错误编号。 2

你的数字是整数,而不是 double ,所以你应该使用:

int a, b, c, d;

将值保存到数组中

首先,让我说,没有充分的理由使用原始数组。您应该始终更喜欢使用标准 ADT,例如 std::vector。

在这种情况下,您不应将值直接读入 vector ,因为该值可能格式不正确。

而是遵循以下顺序:

vector<string> lines;
string line;
while (file >> line) {
  ... // do stuff

  if (successful)
    lines.push_back(line);
}

关于c++ - 如何使用getline从文件中读入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46548438/

相关文章:

c++ - static_assert 和类模板

c - 数组和 while scanf 崩溃

python - 在 Python 中读取 .mat 文件

c++ - 使用 int 作为模式在 C++ 中打开文件

php - Paypal api 将产品插入数组

javascript - SAS 打印到文件

c++ - std::disjunction 在标准库中的实现

c++ - opencv 3.0 findContours 函数在窗口中不起作用

c++ - 在 Windows 上编译 gcc 4.7

arrays - Julia:eigs() 函数不返回所有特征值