visual studio 2010-使用子字符串C++获得奇怪的输出

visual studio 2010 - Getting weird output with substring C++

本文关键字:输出 C++ 字符串 2010- studio visual      更新时间:2023-10-16

所以我遇到了一些奇怪的问题,这似乎是一个非常简单的问题。

我有一个矢量:

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"answers"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);