[英]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.