visual studio 2010-使用子字符串C++获得奇怪的输出
visual studio 2010 - 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"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);
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 将值从二维数组输出到文本文件
- 集合上的输出迭代器:assign和increment迭代器
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 为什么rk4.do_step不输出C++中的初始条件
- 输出没有重复元素的动态数组(收缩数组)C++
- 如何根据单词在文本中出现的概率输出单词