簡體   English   中英

如何在C ++中按char從文件char中讀取?

[英]How to read from a file char by char in C++?

我正在嘗試從文件中讀取內容,但是唯一可以使用的方法是使用getline()。

問題是,整行閱讀不適合我。

我的輸入文件如下所示:

abc 10 20
bbb 10        30
ddd 40 20

每行中的第一個單詞應另存為字符串,然后將兩個數字均另存為int。 每行中“單詞”之間的分隔符可以是SPACE或TAB。

那么唯一的解決方案是逐字符讀取char嗎? 還是有其他解決方案?

假設您想要這樣的東西:

std::string s;
int         v0, v1;
while (in >> s >> v0 >> v1) {
    std::cout << "do something with s='" << s << "' v0=" << v0 << " v1=" << v1 << "\n";
}

但是,這不能確保所有值都在一行上。 如果要安排此操作,則可能要使用std::getline()讀取一行,然后使用std::istringstream將該行如上所述std::istringstream

您可以使用getline()並使函數返回從getline()接收的字符串中的每個連續字符。

對於它的價值,我同意@Dietmar的回答-但我可能會走得更遠。 從外觀上看,每行輸入代表某種邏輯記錄。 我可能會創建一個類來表示該記錄類型,並為該類提供operator>>的重載:

class my_data { 
    std::string name;
    int val1, val2;

    friend std::istream &operator>>(std::istream &is, my_data &m) { 
        std::string temp;
        std::getline(is, temp);
        std::istringstream buffer(temp);
        buffer >> m.name >> m.val1 >> m.val2;
        return is;
    }
};

您可能需要做一些額外的邏輯,以將失敗的轉換在字符串流中傳播到讀取原始數據的istream中。

在任何情況下,都可以(例如)直接從流中初始化對象向量:

std::vector<my_data> whatever(
    (std::istream_iterator<my_data>(some_stream)),
    (std::istream_iterator<my_data>());

我不確定您要什么,我想您想讀取一個文本文件並保存一個字符串和兩個整數(每行)並在新行中打印它們,如果是這樣,請嘗試以下操作:

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

int main()
{
    string str;
    int a,b;
    ifstream file("test.txt");
    if(file.is_open() == false)
        {
        cout << "Error: File can't be loaded" << endl;
        exit(1);
        }
    while(1)    
    {
        if(!file)
        break; 
        file >> str;
        file >> a;
        file >> b;
        cout << str << endl;
        cout << a << endl;
        cout << b << endl;
    }
    file.close(); // Close the file to prevent memory leaks
    return 0;
} 

要按字符讀取文件,同時保留輸入文本格式,可以使用以下命令:

if (in.is_open())
    char c;
    while (in.get(c)) {
        std::cout << c;
    }
}

其中in是類型為std::ifstream的輸入流。 您可以打開這樣的文件,如下所示: std::ifstream in('myFile.txt');

如果您不介意格式化,而是希望將它們全部打印在一行中,則可以遵循DietmarKühl的建議。

@Dietmar的想法是用運算符>>讀取每個單個值,這是一個好主意,但是您在最終行上仍然遇到這個問題。

但是,您不必將整行存儲在臨時字符串中,可以使用std :: istream :: ignore()將其進行流處理並更有效地進行:

bool read_it(std::istream& in, std::string& s, int& a, int& b)
{
  if (in >> s >> a >> b) // read the values
    in.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // read the newline      
  return in;
}

使用fscanf, http: //www.cplusplus.com/reference/clibrary/cstdio/fscanf/

fscanf(stream, "%s %d %d", &s, &a, &b);

暫無
暫無

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

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