如何在C++中逐字符读取文件

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

本文关键字:字符 读取 文件 C++      更新时间:2023-10-16

我正在尝试从文件中读取,但我唯一能做的就是使用getline()。

问题是读一整行对我来说不合适

我的输入文件如下:

abc 10 20
bbb 10        30
ddd 40 20

每行中的第一个单词应保存为字符串,之后两个数字都应保存为int。每行中"单词"之间的分隔符可以是空格或TAB。

那么,唯一的解决方案是逐字符读取吗?或者还有其他解决方案吗?

假设您想要这样的东西:

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如上所述分割这行。

您可以使用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>());

@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;
}

我不完全确定你在要求什么。我想你想读取一个文本文件,保存一个字符串和两个int(每行),并在新行中打印每个int。如果是这样的话,试试这个:

#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;
    }
}

其中CCD_ 6是类型为CCD_。你可以打开这样一个文件,比如:std::ifstream in('myFile.txt');

如果你不介意格式化,宁愿一行打印所有内容,那么你可以听从Dietmar Kühl的建议。

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

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