簡體   English   中英

如何使用 getline 從文件讀取到數組

[英]How to use getline to read from a file into an array

我可以在這個問題上使用你的幫助。 我有一個包含此文件的文件:

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|錯誤:沒有匹配的函數調用'std::basic_ifstream::getline(std::string [10], int)'| |22|錯誤:沒有匹配的函數調用'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

您的數字是整數,而不是雙精度數,因此應使用:

int a, b, c, d;

將值保存到數組中

首先,讓我說,沒有充分的理由使用原始數組。 您應該始終喜歡使用標准ADT,例如std :: vector。

在這種情況下,您不應將值直接讀入向量中,因為該值可能格式錯誤。

而是遵循以下順序:

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

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

這是讀取文件並插入數組的代碼。

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

using namespace std;

const int MAX_LINES = 100;

int main() {
    std::string strArray[MAX_LINES];
    fstream newFile;
    newFile.open("matrix.txt", ios::in); //open a file to perform read operation
    if (newFile.is_open()) {   //checking whether the file is open
        string tp;
        for (int counter = 0; getline(newFile, tp); counter++) { // get new line
            strArray[counter] = tp; // read into string array
            cout << tp << "\n"; //print the string
        }
        newFile.close(); //close the file object.
    }
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM