簡體   English   中英

從C樣式字符串C ++中刪除字符

[英]Removing characters from C-Style string C++

我有一個.txt文件,看起來像這樣...

City- Madrid
Colour- Red
Food- Tapas
Language
Rating

基本上,我想將-或行尾(空格)之前的所有內容添加到一個數組中,並將所有內容添加到第二個數組中。

我的代碼將-whitespace前的所有內容添加到一個數組中,但其余部分則不然。

{
   char** city;
   char** other;
   city = new *char[5];
   other = new *char[5];
   for (int i=0; i<5; i++){
      city = new char[95];
      other = new char[95];
      getline(cityname, sizeof(cityname));
      for(int j=0; j<95; j++){
        if(city[j] == '-'){
             city[j] = city[95-j];
        }
        else{
             other[j] = city[j]; // Does not add the everything after - character
        }
      }
}

如果有人可以用else語句幫助我,我將不勝感激。

如果要編寫C ++代碼,最簡單的方法是只使用std::string 那樣:

std::string line;
std::getline(file, line);
size_t hyphen = line.find('-');
if (hyphen != std::string::npos) {
    std::string key = line.substr(0, hyphen);
    std::string value = line.substr(hyphen + 1);
}
else {
    // use all of line
}

如果要堅持使用C風格的字符串,則應使用strchr

getline(buffer, sizeof(buffer));
char* hyphen = strchr(buffer, hyphen);
if (hyphen) {
    // need key and value to be initialized somewhere
    // can't just assign into key since it'll be the whole string
    memcpy(key, buffer, hyphen); 
    strcpy(value, hyphen + 1);  
}
else {
    // use all of buffer
}

但真的更喜歡std::string

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM