如何从文本文件C++读取整数和特殊字符
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
,但我将留给您(
相关文章:
- 如何在c++中从文本文件中逐行读取整数
- Arduino从Txt读取整数
- 从二进制文件中读取整数数组
- 使用字符串流读取整数并将它们相加
- 如何在从文件中读取整数时使用 file.eof()?
- C++从键盘读取整数的功能
- 为什么字符串流只读取整数中的第一个数字?如何使它只在空白处移动?
- 如何从文本文件C++读取整数和特殊字符
- C++ 从控制台读取整数数组
- 从文本文件中读取整数并将它们存储到数组中
- 输入重定向读取整数和char C
- 从文件读取整数到矩阵 (c++)
- 如何读取整数直到线结束
- 从输入文件读取整数,仅存储数组C 中的唯一整数
- 从文本文件中读取整数
- 读取整数对,直到文本输入文件中的换行符
- 在C++中从文件中读取整数和字符
- 使用 MFC C++ 6.0 从 ms 访问中读取整数数据
- 从标准输入和输入值中读取整数到向量
- 从文件中读取整数到数组