C++ 如何从文本文件C+中读取整数和特殊字符+;
我有这个txt文件:C++ 如何从文本文件C+中读取整数和特殊字符+;,c++,text-files,C++,Text Files,我有这个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;
{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();
}
void文件\u读取器(){
std::ifstream文件(“1000Pairs.txt”,ifstream::in);
std::字符串str;
while(std::getline(文件,str)){
!isalpha(c);}),str.end();
str.erase(std::remove(str.begin()、str.end()、'{','}')、str.end());
cout如上所述,通过尝试擦除
,迭代并键入检查每个字符是否为行,您使这比需要的更难。如果您的格式如您所示{num,c}
,然后您可以使用行上的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 */
...
}
}
#包括
...
无效文件读取器(){
int-num;
字符c;
...
while(std::getline(文件,str)){
字符c1,c2;
std::strings(str);
s>>c1;//带{
s>>num;//读取num
s>>c1>>c2;//带','
s>>c;//读取所需字符
/*您可以根据需要使用'num'和'c'-测试或映射*/
...
}
}
出于您的目的,您可能需要在这里或那里对其进行调整,但这种方法相当简单且健壮。(从技术上讲,您可以在每次读取后检查流状态,以检查badbit
和failbit
,但这将由您决定)如上所述,通过尝试擦除
、迭代并键入检查每个字符是否为行,您使这比需要的更难。如果您的格式如所示{num,c}
,然后您可以使用行上的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 */
...
}
}
#包括
...
无效文件读取器(){
int-num;
字符c;
...
while(std::getline(文件,str)){
字符c1,c2;
std::strings(str);
s>>c1;//带{
s>>num;//读取num
s>>c1>>c2;//带','
s>>c;//读取所需字符
/*您可以根据需要使用'num'和'c'-测试或映射*/
...
}
}
出于您的目的,您可能需要在这里或那里对其进行调整,但这种方法相当简单且健壮。(从技术上讲,您可以在每次读取后检查流状态,以检查badbit
和failbit
,但这将由您决定)你试过写代码吗?你知道地图是什么吗?这是我到目前为止的代码:将它添加到你的问题中--在底部,每行至少缩进4个空格,以便它正确地格式化为代码。抱歉,大卫,我没有看到编辑按钮!哦,你做得比需要的要困难得多。从创建stringstream
ode>line
然后使用strm>>char;
read来去除开头的'{'
,然后strm>>num;
来读取数字,然后strm>>char1>>char2>>char3;
来去除'},
这使您可以准备strm>>charIwant;
读取字符,进行测试,如果测试不满意,则转到下一行。(更简单)。你试过写代码吗?你知道地图是什么吗?这是我到目前为止的代码:将它添加到你的问题中--在底部,每行至少缩进4个空格,以便正确格式化为代码。抱歉,大卫,我没有看到编辑按钮!哦,你做得比需要的要难得多。从创建stringstream
e> 行
然后使用strm>>char;
read来去除开头的'{'
,然后strm>>num;
读取数字,然后strm>>char1>>char2>>char3;
来去除'},
这使您可以准备strm>>charIwant;
读取字符,进行测试,如果测试不满意,则转到下一行。(更简单)。