我正在編寫一個程序,它假設能夠打開一個文件,讀取每一行並分隔一個姓,名:3個測試分數。正在閱讀的文件的格式是馬克泰坦:80 80 85.我想輸出TITAN,馬克:80 80 85.我們正在使用字符串,到目前爲止使用我的教師代碼,我已經得到文件完全分離。它會顯示從1-100開始的測試分數(100首先出現,因爲它以1開頭,但我可以在此之後修復),然後按字母順序排列名稱。我需要幫助創建該行的substr,創建一個完整名稱的字符串並將其分解爲第一個和最後一個,然後正確排序它們。我一直在搞亂.find,但我不知道如何將這個向量分成更小的向量。請幫助和謝謝。C++字符串幫助,隨地吐痰字符串
#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++?](http://stackoverflow.com/questions/236129/split-a-string-in-c) –