我有这个 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++中如何返回对应的字符? 谢谢!!!
最佳答案
如上所述,通过尝试删除
、迭代和类型检查每个字符是行,你正在使这比它需要的更难。如果您的格式如您所显示的那样 {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++ - 如何从文本文件 C++ 中读取整数和特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50462208/