如何在C++中逐字符读取文件
How to read from a file char by char in C++?
我正在尝试从文件中读取,但我唯一能做的就是使用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);
- 尝试一次将单个字符读取到大小不确定的数组中
- C++将 txt 数据和字符读取到 2D 数组中
- C++ UTF-8 瑞典语字符读取为 ASCII
- C++逐个字符读取二进制文件字符
- 逐个字符读取文件并使用<cctype>
- C 如何通过特定n字符读取TXT文件的值
- 如何使用4个字符读取C 的文本文件
- 使用C++中的字符读取具有文件 I/O 的文件
- 是否可以从C 中的文件中的线中的特定字符读取
- 将字符读取到数组
- 如何在 c++ 中逐个字符读取文件并通过 array_name[index] 访问它
- 如何从文本文件中读取,C++中逐个字符读取
- 如何将多个字符读取合并为std::向量
- 在 c++ 中逐个从文件字符读取
- C++ 中有多少个方法逐个字符读取字符串,以对每个字符执行所需的操作
- scanf 只能将 3 个字符读取到 5 位字符数组中
- 将行的前 X 个字符读取为字符串
- 逐个字符读取以查看它是否是数字
- 如何从字符**读取字符串
- 如何逐个字符读取文件的全部内容