[英]Reading a file with c++ containing chars and numbers
我有一个包含某种图形表示形式的文本文件,例如:
7
{5,2,3},{1,5},{},{},{3},{},{}
现在,我知道如何读取文件并进入int
while ((n = myfile.get()) != EOF)
或一行一行地
getline (myfile,line)
我的问题是,使用这两个选项,我似乎无法真正比较提取的每个字符并检查它是数字还是“,”或“ {”或“}”。 有一个简单的方法吗? 从昨天开始,我已经为此动了好几个小时。 我已经尝试了一些等角线和强制转换,但这对我也不起作用,而且真的很复杂。
我认为,最简单的解决方案是通过逐个读取char文件来使您的手有点脏。 我建议您将集合存储在int
向量的向量中(如果需要,可以像2D数组一样可视化它)。
如果第i个集合为空,则第i个向量也将为空。
在解析字符的循环中,将跳过开头的花括号和逗号。 对于右花括号,您将执行类似的操作,除了需要更新索引这一事实之外,这将有助于我们更新第index个向量。
当我们实际读取数字时,可以将char转换为int 。
完整的例子:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main(void) {
char ch;
fstream fin("test.txt", fstream::in);
if(!fin) {
cerr << "Something is wrong...! Exiting..." << endl;
return -1;
}
int N; // number of sets
fin >> N;
vector<vector<int> > v;
v.resize(N);
int i = 0;
while (fin >> ch) {
//cout << ch << endl;
if(ch == '{' || ch == ',')
continue;
if(ch == '}') {
i++;
continue;
}
v[i].push_back(ch - '0');
}
if(i == N) {
cout << "Parsing the file completed successfully." << endl;
} else {
cout << "Parsed only " << i << " sets, instead of " << N << endl;
}
for(size_t i = 0; i < v.size(); ++i) {
if(v[i].size() == 0)
cout << i + 1 << "-th set is empty\n";
else {
for(size_t j = 0; j < v[i].size(); ++j)
cout << v[i][j] << " ";
cout << endl;
}
}
return 0;
}
输出:
gsamaras @ aristotelis:/存储/房屋/ gsamaras $ g ++ main.cpp
gsamaras@aristotelis:/Storage/homes/gsamaras$ ./a.out
Parsing the file completed successfully.
5 2 3
1 5
3-th set is empty
4-th set is empty
3
6-th set is empty
7-th set is empty
重要说明:这应该作为一个起点,因为它不会处理多于一个数字的数字。 在这种情况下,您将阅读逗号或大括号,以确保您阅读数字的所有数字,然后从字符串转换为整数,然后将其存储在相应的向量中。
最好逐个字符地读取,如下所示:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
string line;
int lineNum = 0;
ifstream myfile ("file.txt");
if (myfile.is_open())
{
while ( getline (myfile, line) )
{
// Identifying the type of charcter
char a;
cout << "Line Number " << ++lineNum << ": ";
for(int i = 0; i < line.length(); i++)
{
a = line[i];
cout << "\n\t" << a;
if((a >= 32 && a <= 47) || (a >= 58 && a <= 64) || (a >= 91 && a <= 96) || (a >= 123 && a <= 126))
{
cout << "\t(This character is either a Punctuation or arithmetic mark.)";
// If you don't want to porcess these character, then you may 'continue' to the next sub string
}
else if(a >= 48 && a <= 57)
{
cout << "\t(This character is a number.)";
// If you want to change the number ot int, you can use atoi or stoi
}
else if(a >= 65 && a <= 90)
cout << "\t(Capital letter)";
else if(a >= 97 && a <= 122)
cout << "\t(Small letter)";
}
cout<<endl;
}
myfile.close();
}
else
cout << "Unable to open file";
return 0;
}
我希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.