如何从文本文件C++读取整数和特殊字符

How to read integers and special characters from text file C++

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

我有这个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 */
...
}
}

您可能需要在此处或那里调整它以达到您的目的,但这种方法相当简单和强大。(从技术上讲,您可以在每次读取后检查流状态以检查badbitfailbit,但我将留给您(