2015-10-26 82 views
1

希望有人可以幫助我解決這個問題!GetDlgItem()後修剪CString

我有一個對話框,有幾個組合框填充了數據,用戶應該填寫這些數據,然後單擊保存。當你點擊保存時,程序會創建一個帶有所選數據的輸出文件。

我的問題是,我需要在保存文件前修剪連字符中的所有內容!

組合框填充了字符串看起來是這樣的:

  • 4010-首先
  • 4020-二

而且我希望它看起來像這樣修剪後:

和:

  • PH-彼得·漢森
  • JK-約翰國王

而且我希望它看起來像這樣修剪後:

  • PH
  • JK

我使用Visual Studio 6.0和MFC。

這裏是OnOK代碼:

void CExportChoices::OnOK() 
{ 

CString sFileName, name, height, weight, age, haircolor, eyecolor, initials, group; 


CWnd* pWnd = GetDlgItem(IDC_NAME); 
pWnd->GetWindowText(name); 

sFileName.Format(".\\Export\\%s_export%d.txt", name, GetTickCount()); 
ofstream outfile(sFileName,ios::out); 


pWnd = GetDlgItem(IDC_HEIGHT); 
pWnd->GetWindowText(height); 

pWnd = GetDlgItem(IDC_WEIGHT); 
pWnd->GetWindowText(weight); 

pWnd = GetDlgItem(IDC_AGE); 
pWnd->GetWindowText(age); 

pWnd = GetDlgItem(IDC_HAIRCOLOR); 
pWnd->GetWindowText(haircolor); 

pWnd = GetDlgItem(IDC_EYECOLOR); 
pWnd->GetWindowText(eyecolor); 

pWnd = GetDlgItem(IDC_INITIALS); 
pWnd->GetWindowText(initials); 

pWnd = GetDlgItem(IDC_GROUP); 
pWnd->GetWindowText(group); 


outfile << "Height="  <<  height  <<  "\n"; 
outfile << "\n"; 
outfile << "Weight="  <<  weight  <<  "\n"; 
outfile << "\n"; 
outfile << "Age="   <<  age   <<  "\n"; 
outfile << "\n"; 
outfile << "Hair color=" <<  haircolor <<  "\n"; 
outfile << "\n"; 
outfile << "Eye color="  <<  eyecolor <<  "\n"; 
outfile << "\n"; 
outfile << "Initials="  <<  initials <<  "\n"; 
outfile << "\n"; 
outfile << "Group="   <<  group  <<  "\n"; 

outfile.close(); 

CDialog::EndDialog(22); 

} 

提前感謝!

------------------------------------ UPDATE -------- -----------------------------

好的,經過一番困惑之後,我終於找到了一個適合我的解決方案..

這裏是我試圖你們給我的建議後做:

數據從ComboBox:

「4010團」

我的代碼:

pWnd = GetDlgItem(IDC_GROUP); 
pWnd->GetWindowText(group); 

int i = group.Find("-"); 

if (i >= 0) 
{ 
group = group.Mid(0, i); 

} 

MessageBox(group); // results = 4010-group 

它沒有工作。

我想也許有一些UNICODE相關的問題,所以我改變了數據在ComboBox從「4010團」「4010集團」,並試圖此:

pWnd = GetDlgItem(IDC_GROUP); 
pWnd->GetWindowText(group); 

int i = group.Find(" "); 

if (i >= 0) 
{ 
group = group.Mid(0, i); 

} 

MessageBox(group); // results = 4010 

它的工作原理!但我不明白爲什麼連字符不起作用,有沒有人有線索?

+1

您正在尋找的術語不是修剪,它* substring *。 –

+0

爲什麼不使用CString :: TrimRight方法? –

+0

哦,好吧!那麼我會看一下子字符串!我嘗試過: group.TrimRight(' - '); 但它不適用於我 – tobiasvestlund

回答

3

您可以使用CString::FindCString::Mid,這是類似wstring::findwstring::substr

參見CString functions

CString s = L"4010-First"; 

int i = s.Find('-'); 
if (i >= 0) 
{ 
    s = s.Mid(0, i); 
    TRACE(L"%s\n", s); //output: "4010" 
} 

或獲得第一和第二部分:

CString s1 = s.Mid(0, i); 
CString s2 = s.Mid(i + 1); 
TRACE(L"(%s)(%s)\n", s1, s2); //output: (4010)(First) 
2

這裏有一個解決方案到需要更少代碼的問題。使用一些使用過的和有點誤解的CString方法SpanExcluding,你可以用更少的行完成你的任務。

CString str = L"PH-Peter Hansen"; 
CString newStr = str.SpanExcluding(L"-"); 

將導致只返回「PH」。

2

回覆:「我不明白爲什麼連字符不起作用,有沒有人有線索?」

有很多符號看起來像連字符但不是:dash, en-dash, em-dash, etc.您需要弄清楚在源代碼中使用哪一個符號作爲分隔符。