【发布时间】:2017-10-18 23:44:20
【问题描述】:
我正在编写一个程序,它应该能够打开一个文件,读取每一行并分隔一个 LAST NAME,First name:3 个测试分数。正在读取的文件格式是 Mark Titan:80 80 85。我想输出 TITAN,Mark:80 80 85。我们正在使用字符串,到目前为止,使用我的老师代码我已经将文件完全分开。它将按 1-100 的顺序显示测试分数(100 排在第一位,因为它以 1 开头,但我可以在之后修复它),然后按字母顺序显示名称。我需要帮助创建该行的子字符串,创建一个仅包含全名的字符串并将其拆分为第一个和最后一个,然后正确排序。我一直在搞乱 .find 但我不确定如何将此向量拆分为更小的向量。请帮忙,谢谢。
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
using namespace std;
void openFile(ifstream &in);
void processFile(ifstream &in, vector<string> &list);
void display(const vector<string> &list);
void sort(vector<string> &list);
int main(int argc, char *argv[])
{
ifstream in;
string line;
vector<string> words;
openFile(in);
processFile(in, words);
display(words);
return 0;
}
void openFile(ifstream &in)
{
string fileName;
bool again;
do
{
again = false;
cout<<"What is the name of the file to you wish to sort? (.txt will be added if no extension is included): ";
cin>>fileName;
if(fileName.find('.') >= fileName.size() )
fileName += ".txt";
in.open(fileName.c_str());
if(in.fail())
{
in.close();
in.clear();
again = true;
cout<<"That file does not exist! Please re-enter"<<endl;
}
}while(again);
}
void processFile(ifstream &in, vector<string> &list)
{
string line, word;
int s1,s2,s3;
stringstream ss;
while(getline(in, line, ':'))
{
ss<<line.substr(line.find(' ') + 1);
while(ss>>word)
list.push_back(word);
ss.clear();
}
sort(list);
}
void sort(vector<string> &list)
{
for(unsigned int i = 0; i < list.size(); ++i)
for(unsigned int j = 0; j < list.size(); ++j)
if(list[i] < list[j])
{
string temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
void display(const vector<string> &list)
{
cout<<"The file read had "<<list.size()<<" words in it"
<<endl<<"In sorted order, they are:"<<endl;
for(unsigned int i = 0; i < list.size();++i)
cout<<list[i]<<endl;}
【问题讨论】:
标签: c++ string c++11 vector split