我正在使用 getline 读取到换行符的结尾,但是 c++ getline 让我的东西直到空间,
我有 txt 文件数据为
地址(tab char)1420欢乐巷
当我做
getline(reader, ss, '\t') 我在 ss 字符串中获取地址。当我做 getline(reader, ss, '\n') 我只得到 1420。
我想要完整的《1420欢乐巷》,如何获得?
谢谢。
#include <fstream>
#include <string>
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
int main( int argc, char *argv[] )
{
if( argc < 2 )
{
cout << "Missing filename as first argument" << "\n";
exit(2);
}
vector<string> myvector;
string ss;
int i=0, j=0;
ifstream reader(argv[1]);
if (! reader )
{
cout << "Error opening input file : " << " " << argv[1] << '\n';
return -1;
}
while( !reader.eof())
{
if ((i+1) % 2 == 0 )
getline(reader, ss, '\n');
else
getline(reader, ss, '\t');
if (ss[0] == '#')
{
//Skip
getline(reader,ss, '\n');i=0;
continue;
}
i++;
myvector.push_back(ss);
}
reader.close();
vector<string>::iterator it;
stringstream stream;
int vecloc=1;
string tag;
string sData;
cout << "myvector contains: \n";
for ( it=myvector.begin() ; it < myvector.end(); it++ )
{
switch (vecloc)
{
case 1: stream << *it; stream >> tag; vecloc++;break;
case 2:
stream << *it; stream >> sData;
// Do job
cout << tag << " " << sData << "\n";
// Reset.
vecloc=1; break;
default : break;
}
// Clear String stream
stream.str(""); stream.clear();
}
return(0);
}
输出
/home/sr/utl
猫 abc.txt
嘿 C++ 让我发疯。
/home/sr/utl
a.out abc.txt
myvector 包含:
嘿 c++