簡體   English   中英

C++ 無法將字符串添加到數組

[英]C++ can't add string to array

我試圖逐行讀取文件並將這些行插入到數組中,但它不會編譯。 我正在使用 VS 代碼,它突出顯示了 arr[line],當我輸入 hover 時,它說“沒有運算符“[]”匹配這些操作數”。 有人可以告訴我我做錯了什么嗎?

#include <fstream>
#include <string>
#include <iostream>
using namespace std;
   
int main() {
    char arr[4];
    string line;

    ifstream file;
    file.open("input.txt");
        if(file.is_open()) {
            while (getline(file, line))
        {
            file >> arr[line];  // the problem is with this line
        }
        file.close();
        }
    return 0;
}

您正在嘗試訪問一個數組,使用字符串作為索引,這在 C++ 中是無效的。

用簡單的英語來說,這意味着您告訴編譯器“將索引為 line 的數組中的數據存儲到文件中”。

然后編譯器不知道你想做什么,因為字符串不是數組索引支持的類型。

我建議在這里閱讀更多關於索引 arrays 的信息: https://www.cpp.edu/~elab/ECE114/Array.html

您可以嘗試使用位於此處的代碼: How to read lines of text from file and put them into an array

您的代碼有一些改進 scope。 當您從文件中讀取時,您不知道它包含多少行。 因此,要存儲這些行而不是使用固定大小的容器(如數組),請嘗試使用動態大小的容器(如向量)。

這是例子:

#include <fstream>
#include <string>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<string> mylines;
    string line;

    ifstream file;
    file.open("input.txt");
    
    if(file.is_open()) {
        while (getline(file, line))
        {
            mylines.push_back(line);
        }
        file.close();
    }
    for(int i=0;i<mylines.size();i++)
           cout<<mylines[i]<<endl;
   return 0;
}

暫無
暫無

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

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