[英]Getting weird output with substring C++
所以我在看起來很簡單的問題上遇到了一些奇怪的問題。
我有一個向量:
vector(string)collectionOfLines;
這保存了我從.txt文件中獲得的文本行。 文本文件的內容為:
“ 4
磁盤0.2 0.00005
鼠標0.4 0.00002
鍵盤0.3 0.00004
網絡0.5 0.0001“
collectionOfLines [0] =“磁盤0.2 0.00005”
我正在嘗試將此字符串分成三個不同的字符串:“ Disk”,“ 0.2”和“ 0.00005”,然后將這些字符串放入不同的向量中:
vector(string)collectionOfCommands;
這是我從循環字符串獲取子字符串並將其放入新向量的循環。
string deviceName;
string interruptProbability;
string interruptTime;
for(int i = 1; i < collectionOfLines.size(); i++) { // i = 1 because I am ignoring the "4" in the txt file
string currentLine = collectionOfLines[i];
int index = 0;
for(int j = 0; j < currentLine.length(); j++) {
if(j == 0) {
continue;
} else if(deviceName.empty() && currentLine[j-1] == ' ') {
deviceName = currentLine.substr(index, j-1);
index = j;
} else if (interruptProbability.empty() && currentLine[j-1] == ' ') {
interruptProbability = currentLine.substr(index, j-1);
index = j;
} else if (!deviceName.empty() && !interruptProbability.empty()) {
interruptTime = currentLine.substr(index, currentLine.length());
break;
} else {
continue;
}
}
collectionOfCommands.push_back(deviceName);
collectionOfCommands.push_back(interruptProbability);
collectionOfCommands.push_back(interruptTime);
}
當我運行它時,我沒有收到任何錯誤,但是當我打印collectionOfCommands的輸出時,我得到了:
“磁盤
0.2 0.00
0.00005
磁碟
0.2 0.00
鼠標0.4 0.00002
磁盤0.2 0.00
鍵盤0.3 0.00004
磁盤0.2 0.00
網絡0.5 0.0001“
顯然,除了第一個輸出“磁盤”之外,此輸出是完全錯誤的。
幫助將不勝感激,謝謝!!
這是一種拆分字符串的怪異方法,特別是因為您已經知道一致的格式。 您使用substr()是否有特殊原因? 嘗試改用輸入字符串流。
#include <sstream>
#include <string>
...
istringstream iss(currentLine);
getline(iss, deviceName, ' ');
getline(iss, interruptProbability, ' ');
getline(iss, interruptTime);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.