求助!!!c++从txt文件中读取数据的问题,有转义字符

txt中以一段数据是 1\t2\t3\r\n
如果是1,2,3形式我会读取,但是出现转义字符再用if(ch=‘,’)infile>>a>>ch;的形式‘\t’就不可以了,怎么解决啊

// Try
#include <iostream>
#include <string>
#include <ostream>
#include <fstream>

using namespace std;

static char buffer[256];

void OutputDigits(const char buf[256])
{
  int i=0;
  while(buf[i])
  {
  if(isdigit(buf[i]))
  {
         cout<<buf[i]<<" ";
 i++;
  }
  else
  {
         i++;
 continue;
  }
  }
 cout<<endl;
}
int main(void)
{
     ifstream myfile("test.txt");
     while(!myfile.eof()){
 myfile.getline(buffer,100);
 }
 
 cout<<"before:"<<buffer<<endl;
 cout<<"after:";
 OutputDigits(buffer);
return 1;
}

温馨提示:内容为网友见解,仅供参考
第1个回答  2013-10-21

这个应该可以满足你,用getline读取,然后按照分隔符分割,有什么阻碍的你就在 isNeed 函数里的 switch 里面添加条件就好了

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;

bool IsNeed(char c)
{
switch(c)
{
case ',':return false;break;
case '\t':return false;break;
case ' ':return false;break;
default:return true;break;
}
}
int main()
{
int i,len;
string str;
char s[10000];
ifstream in("a.txt");
while(!in.eof())
{
in.getline(s,10000);
len = strlen(s);
str = "";
for(i=0;i<len;i++)
{
if(IsNeed(s[i]))
{
str+=s[i];
}
else
{
if(str == "")
continue;
cout<<str<<endl;
str="";
}
}
}
system("pause");
return 0;
}

本回答被提问者采纳
第2个回答  2013-10-21
试试sstream:

ifstream fi("d:\\1.txt");
while(getline(fi, string)) {
sstream s(string);
char c;

while(s>>c);

}
第3个回答  2013-10-21
试试这样。

ifstream fi("d:\\1.txt");
char a,b,c;
fi.get(a);
fi.get(b);
fi.get(c);
cout << a << b << c << "end"<< endl;追问

可是我要读的数据有好多行,要是一个一个读有些麻烦。
有没有其他的办法呢?

追答

用getline呢。
#include
#include
#include
using namespace std;
int main()
{
string tmp;
string content;
fstream fs("d:\\1.txt");
while( getline(fs,tmp) ){
content+=tmp;
content+="\n";
}
cout << content << endl;
return 0;
}