2014-04-04 21 views
0

分開後,我有這樣一個文件:C++:從文件中分離的姓和名,中間用逗號

Collins,Bill 80 
Smith,Bart 75 
Allen,Jim 82 
Griffin,Jim 55 
Stamey,Marty 90 
Rose,Geri 78 
Taylor,Terri 56 
Johnson,Jill 77 
Allison,Jeff 45 
Looney,Joe 89 
Wolfe,Bill 63 
James,Jean 72 
Weaver,Jim 77 
Pore,Bob 91 
Rutherford,Greg 42 
Javens,Renee 74 
Harrison,Rose 58 
Setzer,Cathy 93 
Pike,Gordon 48 
Holland,Beth 79 

正如你所看到的姓氏和名字都用逗號分隔。

現在我有這個在我的代碼:

ifstream inputFile; 
inputFile.open ("students.txt"); 

string studentNames;   // Student names - Last name followed by first 
int studentMarks = 0;   // Student mark for text/exam 

// Read in data from students.txt 
inputFile >> studentNames; 
inputFile >> studentMarks; 

// IF file has too much data, output WARNING 
if (numElts >= NUM_NAMES) 
{ 
    cout << "Error: File contains too many lines of data, check the file." << endl << endl; 
} 
else 
{ 
    names[numElts] = studentNames; 
    marks[numElts] = studentMarks; 
    numElts++; 
} 

我想繞過這些逗號,我想保存它作爲名字,然後,然後我將只合併到名稱類似name = firstname " " last name姓氏。我應該怎麼做?

+2

1.閱讀在整個'名字,lastname'令牌作爲目前工作。 2.用'string :: find()'查找逗號的位置。 3.用這些信息創建2個新的子字符串。 –

+0

等待如何使用此查找,以便在inputFile >> studentNames下面;我會把studentNames.find(「,」);但那又如何?我如何擺脫它,或者在找到這個逗號後該做什麼? – tinywolves

+0

如果您無法弄清楚我剛纔所說的和* 90秒*在Google上做什麼,那麼我很抱歉,但您對這類練習的理解深度已經過去了。您需要了解一個字符串是什麼以及首先可以對其執行的各種基本操作。 –

回答

0

使用此功能可以去除,並獲得最後與空間之間的第一個名字,

string output; 
    int position = studentNames.find(','); 
    for(int i=position+1;i<studentNames.size();i++) 
     output+=studentNames[i]; 
    output+=' '; 
    for(int i=0;i<position;i++) 
     output+=studentNames[i]; 
    studentNames = output; 
+0

我不認爲我們被允許使用額外的功能。我僅限於一些被設立並被告知要在那些工作中工作的人,所以我不能。所有這些都已經在一個函數中。 – tinywolves

+0

編輯答案。 – Tahlil

+0

因此,雖然數據是姓氏,名字,這將切換到第一個和最後一個?它是如何做到的?它抓住了兩個名字? – tinywolves

1
std::string::size_type commaPos = studentName.find(","); 
std::string studentLastName = studentName.substr(0, commaPos); 
std::string studentFirstName = studentName.substr(commaPos + 1); 
+0

我真的很新C++,我不明白什麼::用作和我使用命名空間標準;在頂部。這是我第一個C++類。第一個喜歡讓我困惑,所以我想明白。 – tinywolves

+0

閱讀以瞭解有關http://www.learncpp.com/cpp-tutorial/711-namespaces/ – Tahlil

+0

中的命名空間的信息,謝謝該鏈接非常有幫助,因爲我們的教授根本沒有真正解釋這些內容。 – tinywolves