繁体   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