【发布时间】:2016-01-20 14:11:36
【问题描述】:
我正在尝试从用户那里获取包含 part1/1 part2/4 等条目的 txt 文件,并将其存储在向量“part_name”和“rev_id”中。所以“part_name”包含 part1 part2 ... 而“rev_id”包含 1 4 ..... 该程序在命令提示符下作为 program.exe list.txt 运行。
当 txt 文件有 2 个或更多输入时,程序运行良好,但当它有单个输入时,vector 大小显示为 2(但必须为 1)。
即
如果list.txt 包含part1/1 part2/4 => part_name.size() 是2
如果 list.txt 包含 part1/1 => part_name.size() 仍然是 2。
有人可以帮我解决这个问题吗?
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
int main(int argc, char*argv[])
{
std::string s ;
std::string delimiter = "/";
size_t pos;
std::vector<std::string> part_name;
std::vector<std::string> rev_id;
std::string token1,token2;
ifstream readFile (argv[1]);
if (readFile.is_open())
{
while (!readFile.eof())
{
readFile >> s;
pos=s.find(delimiter);
if((pos!=std::string::npos)&&(pos!=0))
{
token1 = s.substr(0, s.find(delimiter));
token2 = s.substr(pos + delimiter.length());
part_name.push_back(token1);
rev_id.push_back(token2);
}
}
}
else{
std::cout<<"Cannot open file"<<endl;
}
readFile.close();
for (unsigned j=0; j < part_name.size(); j++)
{
cout<<part_name.size()<<endl;
cout<<"part name j is " <<part_name[j]<<endl;
cout<<"part id j is " <<rev_id[j]<<endl;
}
}
【问题讨论】:
-
part1/1是单独一行还是每行可以有多个“部分”?