[英]How to read integers and special characters from text file C++
我有這個txt文件:
{8500, X }
{8600, Y }
{8700, Z }
{8800, [ }
{8900, \ }
{9000, ] }
{9100, ^ }
{9200, _ }
{9300, ` }
{9400, a }
{9500, b }
{9600, c }
到目前為止,這是我的代碼:
void file_reader(){
std::ifstream file("1000Pairs.txt", ifstream::in);
std::string str;
while (std::getline(file, str)){
!isalpha(c); } ), str.end());
str.erase(std::remove(str.begin(), str.end(), '{', ',', '}'), str.end());
cout << str << endl;
//int_reader(str, array); // adds the integers to the array
}
file.close();
}
給定一個整數,我該如何在C ++中返回相應的字符? 謝謝!!!
如上所述,通過嘗試erase
,迭代和類型檢查每個字符是否為一行,您正在使此字符變得比所需的難。 如果您的格式如顯示{num, c }
,則可以通過line
上使用stringstream
大大簡化讀取過程。 這樣,您可以只使用常規>>
輸入運算符和正確的類型來讀取所需的數據,並丟棄不需要的字符,例如:
#include <sstream>
...
void file_reader(){
int num;
char c;
...
while (std::getline(file, str)){
char c1, c2;
std::stringstream s (str);
s >> c1; // strip {
s >> num; // read num
s >> c1 >> c2; // strip ', '
s >> c; // read wanted char
/* you have 'num' and 'c' - test or map as needed */
...
}
}
您可能需要根據自己的目的在此處或此處進行調整,但是這種方法非常簡單且健壯。 (從技術上講,您可以在每次讀取后檢查流狀態,以檢查badbit
和failbit
,但我badbit
您自己決定)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.